Appearance
Generics
Generics enable you to write type-safe and reusable code that can work with different data types. They provide better performance and type safety compared to using object types and runtime type checking.
Generic Classes
Generic classes allow you to define classes that can work with different types while maintaining type safety. This enables code reuse without sacrificing performance or type checking.
csharp
public class GenericList<T>
{
private T[] items;
public void Add(T item)
{
// Add implementation
}
public T GetItem(int index)
{
return items[index];
}
}
Generic Methods
Generic methods allow you to define methods that can work with different types while maintaining type safety at compile time.
csharp
public T Max<T>(T first, T second) where T : IComparable<T>
{
return first.CompareTo(second) > 0 ? first : second;
}
Generic Constraints
Constraints allow you to restrict which types can be used with a generic class or method, ensuring that the type arguments have the necessary capabilities.
csharp
// Type constraint
class DataStore<T> where T : class
// Interface constraint
class Calculator<T> where T : IComparable<T>
// Constructor constraint
class Factory<T> where T : new()
// Multiple constraints
class KeyValuePair<TKey, TValue>
where TKey : struct
where TValue : class, new()