How to create a generic class and method in C#?

Asked 27-Aug-2021
Viewed 714 times

2 Answers


0

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';

0

We can create a generic class in C# that can be used with objects of any type. This type of class is called Generic Class. We can also create a generic method like a generic class which can be called with any type of argument. The compiler handles each method based on the arguments passed to the generic method.
Type Parameters
    The naming convention of type parameters is very important to learn generics.
1. T – Type
2. E - Element
3. K – Key
4. N – Number
5. V – Value
Syntax
Class class-name<T>

 {
      access-modifier datatype method-name(){
      }
      access-modifier T method-name(){
      }
 }
Example
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
 }
}
Output
Ashu

Anupam
Manish
Sunny
Shyam