C# Generics

Like it's name, Generics is a data type wildcard. If a class or function handles different data types at different occasions, you may not want to specify the data type of the parametera, then Generics can be used as a place holder.

//using Generics in a class
class tt<T>
{
public string add(T a,T b)
{
string c= a.ToString() + " " + b.ToString();
return c;
}
}
tt<int> t = new tt<int>();
string ret = t.add(3,4); //3 4
tt<double> t2 = new tt<double>();
string ret2 = t2.add(3,4.54); //3 4.54
tt<string> t3 = new tt<string>();
string ret3 = t3.add("orange","good"); //orange good

Using Generics in a function.
public string add<T>(T a,T b)
{
string c= a.ToString() + " " + b.ToString();
return c;
}
string ret = add(3,4); //3 4
string ret2 = add(3,4.54); //3 4.54
string ret3 = add("orange","good"); //orange good

The System.Collections.Generic class contains a lot of Generics classes including List, Dictionary, Queue, KeyValuePair etc.

endmemo.com © 2024  | Terms of Use | Privacy | Home