Generic Class in C#
Generic classes in C# was introduced in C# 2.0. A generic class is introduced for type safety. Using generics, C# class may work as a placeholder for any data type. Angle brackets are used to define generic class in C#. Good understanding of generics is necessary to understand various designing patterns.
Here we can see a very simple example of generic.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharp_Test
{
class Program
{
static void Main(string[] args)
{
myclass obj = new myclass { id = 1, name = "yogesh" };
List<myclass> obj1 = new List<myclass>
{
new myclass{ id=1, name="yogesh" },
new myclass{ id=2, name="yogesh1" },
new myclass{ id=3, name="yogesh2" }
};
genclass<int> obj5 = new genclass<int>(20);
Console.WriteLine("Generic Variable is "+obj5.genvariable);
genclass<string> obj6 = new genclass<string>("ceg123");
Console.WriteLine("Generic Variable is with string " + obj6.genvariable);
genclass<myclass> classobj = new genclass<myclass>(new myclass { id=12, name = "Vikas Sharma" });
Console.WriteLine("Generic Variable of class is with string " + classobj.genvariable.id+" "+classobj.genvariable.name);
foreach (var obj2 in obj1)
{
Console.WriteLine(obj2.name);
}
Console.ReadLine();
}
}
class myclass
{
public string name;
public int id;
}
public class genclass<T>
{
public T genvariable;
public genclass(T value)
{
this.genvariable = value;
}
public T generimethod()
{
return this.genvariable;
}
}
}
Generics classes are used for code reusability. T is used as a placeholder. It improves the performance of the program due to the unavailability of boxing and unboxing.