C#: Generic classes

We have looked at generic method but in C#, generic classes are also used widely.

Generic classes allow operations that are not specific to a particular data type.  Usually, those data types are of type integer or string.

If you look at programming literature related to WPF, you will come across this symbol <> quite frequently.

The symbol <> actually denotes either generic method, class or generic interface.

Generic classes are used commonly in WPF such as this ObservableCollection class where it is used to track items in a list or combo box.

using System;

class Mix<T,U>
{
    T val1;
    U val2;

    public Mix(T t, U u)
    {
        // The field has the same type as the parameter.
        this.val1 = t;
        this.val2 = u;
    }

    public void Write()
    {
        Console.WriteLine(this.val1);
        Console.WriteLine(this.val2);
    }

    public void Write1()
    {
        Console.WriteLine("I have " + this.val1 + " " + this.val2);
    }
}

class Program
{
    static void Main()
    {
        Mix<int, int> m1 = new Mix<int, int>(5, 6);
        m1.Write();
        Console.WriteLine();
        Mix<int, string> m2 = new Mix<int, string>(5,"cats");
        m2.Write1();
        Console.ReadKey();
    }
}

In this example, the class Mix will be able to take in either integers or strings.  In the class declaration, we use <T,U> and in fact they can be any letter or combination of letters.

 

Series Navigation<< C#: Generic method for reversing an array
C#: A generic class called Collection >>