How to create a generic class and method in C#?
How to create a generic class and method in C#?
2 Answers
You can create an instance of generic classes by specifying an actual type in angle brackets. The following creates an instance of the generic class
DataStore.
DataStore<string> store = new DataStore<string>();
Above, we specified the string type in the angle brackets while creating an instance. So,
T will be replaced with a string type wherever T is used in the entire class at compile-time. Therefore, the type of
Data property would be a string.
You can assign a string value to the Data property. Trying to assign values other than string will result in a compile-time error.
DataStore<string> store = new DataStore<string>();
store.Data = 'Hello World!';
//store.Data = 123; //compile-time error
You can specify the different data types for different objects, as shown below.
DataStore<string> strStore = new DataStore<string>();
strStore.Data = 'Hello World!';
//strStore.Data = 123; // compile-time error
DataStore<int> intStore = new DataStore<int>();
intStore.Data = 100;
//intStore.Data = 'Hello World!'; // compile-time error
KeyValuePair<int, string> kvp1 = new KeyValuePair<int, string>();
kvp1.Key = 100;
kvp1.Value = 'Hundred';
KeyValuePair<string, string> kvp2 = new KeyValuePair<string, string>();
kvp2.Key = 'IT';
kvp2.Value = 'Information Technology';
Class class-name<T>
{
access-modifier datatype method-name(){
}
access-modifier T method-name(){
}
}
using System;
//Generic Class
class Genericdemo <T>
{
//Generic property
private T[] _data = new T[10];
public void AddOrUpdate(int index, T item)
{
if(index >= 0 && index < 10)
_data[index] = item;
}
//Generic Method
public T GetData(int index)
{
if(index >= 0 && index < 10)
return _data[index];
return default(T);
}
}
public class Program
{
public static void Main()
{
Genericdemo<string> gd= new Genericdemo<string>(); //Generic class object
gd.AddOrUpdate(0,'Ashu');
gd.AddOrUpdate(1,'Anupam');
gd.AddOrUpdate(2,'Manish');
gd.AddOrUpdate(3,'Sunny');
gd.AddOrUpdate(4,'Shyam');
for(int i=0;i<7;i++)
Console.WriteLine(gd.GetData(i)); //Generic Method calling
}
}
Ashu
Anupam
Manish
Sunny
Shyam