Friday, 12 April 2013

Generic Types in C#: Syntax and Example

Generic Types in C#: Syntax and Example

Generic classes have type parameters. Separate classes, each with a different field type in them, can be replaced with a single generic class. The generic class introduces a type parameter. This becomes part of the class definition itself.

These types themselves contain type parameters, which influence the compilation of the code to use any type you specify.

Common examples of generics are Dictionary and List.

Program that describes generic class C#

using System;
class Test<T>
{
    T _value;
    public Test(T t)
    {
       // The field has the same type as the parameter.
       this._value = t;
    }
    public void Write()
    {
      Console.WriteLine(this._value);
    }
}

class Program
{
    static void Main()
    {
      // Use the generic type Test with an int type parameter.
      Test<int> test1 = new Test<int>(5);
      // Call the Write method.
      test1.Write();
      // Use the generic type Test with a string type parameter.
      Test<string> test2 = new Test<string>("cat");
      test2.Write();
    }
}

Output
5
cat

1 comment:

  1. Very simple and clear example. Thanks!

    ReplyDelete