Generic Class C#
Generic Class C# is a class that accepts type parameters so it’s encapsulated operations can be useful to any data type. Defining a generic class is as simple as defining a generic method. It has a similar syntax of using angle brackets and specifying a type parameter. The following program shows an example of a generic class.
using System;
namespace GenericClassDemo
{
public class GenericClass<T>
{
private T someField;
public GenericClass(T someVariable)
{
someField = someVariable;
}
public T SomeProperty
{
get { return someField; }
set { someField = value; }
}
}
public class Program
{
public static void Main()
{
GenericClass<double> genericDouble = new GenericClass<double>(30.50);
GenericClass<int> genericInt = new GenericClass<int>(10);
Console.WriteLine("genericDouble.SomeProperty = {0}",
genericDouble.SomeProperty);
Console.WriteLine("genericInt.SomeProperty = {0}",
genericInt.SomeProperty);
genericDouble.SomeProperty = 100.32;
genericInt.SomeProperty = 50;
}
}
}
Example 1 – Creating a Generic Class
genericDouble.SomeProperty = 30.50 genericInt.SomeProperty = 10
We created a generic class that has a field, property and a constructor (Lines 5-19). All the occurrences of T will be substituted by the type that will be indicated when we create the generic class. When creating a new instance of our generic class, we specify the type inside the angle brackets. Like generic methods, you can also specify multiple type parameters for a generic class.
public class GenericClass<T1, T2, T3>
{
private T1 someField1;
private T2 someField2;
private T3 someField3;
}
You cannot create new objects of type T1, T2 or T3 because you don’t know what types they actually are so the following is not allowed.
public GenericClass //Constructor
{
someField1 = new T1();
someField2 = new T2();
someField3 = new T3();
}
Non-generic class can inherit generic classes. But you must define a type of the type parameter for the generic base class.
public class MyClass : GenericClass<int>
{
}
A generic class can also inherit a non-generic class.