Wednesday, October 21, 2009

Generics

Generics allow us to create classes that are not bound to a specific type, and must provide generic functionality for all types. It can be used to provide type-safety during compile-time.

Here is a sample program I wrote to demonstrate how to create a Generic class. I intentionally avoided using for the type, to show this is not a requirement.


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;

namespace SystemTypesCollections
{
public class GenericsTest<ZX>
{
public ZX MyVal { get; set; }

public override string ToString()
{
if (MyVal is String)
{
return "My String is: '" + MyVal + "'";
}
else if (MyVal is int)
{
return "I am an Integer: " + MyVal;
}
else
{
return "I am an object";
}

}
public GenericsTest(ZX val)
{
MyVal = val;
}
}

public class Program
{
static void Main(string[] args)
{
GenericsTest<int> g1 = new GenericsTest<int>(5);
GenericsTest<String> g2 = new GenericsTest<string>("Hello, world");
GenericsTest<IList> g3 = new GenericsTest<IList>(new ArrayList());

System.Console.WriteLine(g1);
System.Console.WriteLine(g2);
System.Console.WriteLine(g3);
}
}
}



Output result:
I am an Integer: 5
My String is: 'Hello, world'
I am an object

No comments:

Post a Comment