In C#, Generic classes and methods combine reusability, efficiency, and type safety in a way that their non-generic counterparts cannot.
Generics allow defining the specification of the data type of C# programming elements in a class or a method. Generic class, must use angle <> brackets.The angle brackets are used to declare a class or method as generic type.
C# Generic class example
using System;
namespace CSharpProgram
{
public class GenericClass<T>
{
public GenericClass(T message)
{
Console.WriteLine(message);
}
}
public class Program
{
public static void Main(string[] args)
{
GenericClass<string> objGenString = new GenericClass<string> ("This is generic class Example");
GenericClass<int> objGenint = new GenericClass<int>(101);
GenericClass<char> objGenCh = new GenericClass<char>('I');
}
}
}
Output
This is generic class Example
101
I
Generic Method Example
using System;
namespace CSharpProgram
{
public class GenericClassExample
{
public void Show<T>(T message)
{
Console.WriteLine(message);
}
}
public class Program
{
public static void Main(string[] args)
{
GenericClassExample genC = new GenericClassExample();
genC.Show("This is generic method Example");
genC.Show(101);
genC.Show('I');
}
}
}
Output
This is generic method Example
101
I