Menus

Sunday, December 9, 2012

Generic classes with more example in c#

Generic classes provide generic nature to classes and data member datatypes. When creating Generic classes we will create classes, data members ... we will define with place holders <>
Class classname <Placeholder>
{
...
}
While creating object for the generic class we will specify the data type, then onwards class will bind to specific data type

classname<int> obj = new classname<int>();

Example

public class Generic<T>
{
// Data Member
T empID;

// Constructor
public Generic(T eVal)
{
empID = eVal;
}

public void Show()
{
Console.WriteLine("Employee Id - {0}", empID);
}

}

public class MainClass
{
public static void Main()
{
Generic<int> genObj1=new Generic<int>(20);
genObj1.Show();
Generic<string> genObj2=new Generic<string>("EMP1");
genObj2.Show();
}
}


In the above example while we are creating instance, if we pass the place holder value then the class will be created in the inline memory withe the specified type.

No comments:

Post a Comment