Generics in C# provide flexibility and type safety for classes, methods, interfaces, and more. This blog explores different types of generics in C# with examples.
public class GenericClass
{
private T data;
public void SetValue(T value) => data = value;
public T GetValue() => data;
}
// Usage
var intInstance = new GenericClass();
intInstance.SetValue(10);
Console.WriteLine(intInstance.GetValue()); // Output: 10
var stringInstance = new GenericClass();
stringInstance.SetValue("Hello");
Console.WriteLine(stringInstance.GetValue()); // Output: Hello
public class GenericMethods
{
public void Print(T value)
{
Console.WriteLine(value);
}
}
// Usage
var obj = new GenericMethods();
obj.Print(123); // Output: 123
obj.Print("Generics"); // Output: Generics
public interface IGenericInterface
{
T Process(T input);
}
public class GenericImplementation : IGenericInterface
{
public int Process(int input) => input * 2;
}
// Usage
var instance = new GenericImplementation();
Console.WriteLine(instance.Process(5)); // Output: 10
public delegate T GenericDelegate(T input);
class Program
{
public static int Double(int x) => x * 2;
public static string Uppercase(string x) => x.ToUpper();
static void Main()
{
GenericDelegate intDelegate = Double;
Console.WriteLine(intDelegate(5)); // Output: 10
GenericDelegate stringDelegate = Uppercase;
Console.WriteLine(stringDelegate("hello")); // Output: HELLO
}
}
public class GenericWithConstraints where T : class
{
public T Value { get; set; }
}
// Usage
var instance = new GenericWithConstraints { Value = "Hello" };
Console.WriteLine(instance.Value); // Output: Hello
public struct GenericStruct
{
public T Value { get; set; }
}
// Usage
var genericStruct = new GenericStruct { Value = 42 };
Console.WriteLine(genericStruct.Value); // Output: 42
public class GenericEnum where T : Enum
{
public T EnumValue { get; set; }
}
// Usage
var enumInstance = new GenericEnum { EnumValue = DayOfWeek.Monday };
Console.WriteLine(enumInstance.EnumValue); // Output: Monday
public class GenericEvent
{
public event Action OnValueChanged;
public void Trigger(T value)
{
OnValueChanged?.Invoke(value);
}
}
// Usage
var eventInstance = new GenericEvent();
eventInstance.OnValueChanged += value => Console.WriteLine($"Value changed to: {value}");
eventInstance.Trigger("New Value"); // Output: Value changed to: New Value
C# offers several built-in generic collections:
List
Dictionary
Queue
Stack
Generics in C# are a powerful tool that provides flexibility, type safety, and performance. Use these examples to explore and master the world of generics in your applications.