generics in c# code example

Example 1: generics in c#

class MyGenericClass
{
    private T genericMemberVariable;

    public MyGenericClass(T value)
    {
        genericMemberVariable = value;
    }

    public T genericMethod(T genericParameter)
    {
        Console.WriteLine("Parameter type: {0}, value: {1}", typeof(T).ToString(),genericParameter);
        Console.WriteLine("Return type: {0}, value: {1}", typeof(T).ToString(), genericMemberVariable);
            
        return genericMemberVariable;
    }

    public T genericProperty { get; set; }
}

Example 2: generics in c#

class DataStore
{
    public T Data { get; set; }
}

Example 3: c# collection of generic classes

public abstract class MyClass
{
    public abstract Type Type { get; }
}

public class MyClass : MyClass
{
    public override Type Type
    {
        get { return typeof(T); }
    }

    public T Value { get; set; }
}

// VERY basic illustration of how you might construct a collection
// of MyClass objects.
public class MyClassCollection
{
    private Dictionary _dictionary;

    public MyClassCollection()
    {
        _dictionary = new Dictionary();
    }

    public void Put(MyClass item)
    {
        _dictionary[typeof(T)] = item;
    }

    public MyClass Get()
    {
        return _dictionary[typeof(T)] as MyClass;
    }
}

Example 4: generic method c#

//Swaps the lhs and rhs variables. T is a type given as an argument 
//and can be used in the method like a type. (It doesn't have to be "T", it can
//be anything).

static void Swap(ref T lhs, ref T rhs)
{
    T temp;
    temp = lhs;
    lhs = rhs;
    rhs = temp;
}

public static void TestSwap()
{
    int a = 1;
    int b = 2;

    Swap(ref a, ref b);
    System.Console.WriteLine(a + " " + b);
}

Tags:

Misc Example