Coding Schools


 
Python | C Sharp | Azure AI | HTML | JavaScript | CSS | SQL Server
OOPS in C#
C# Data Types
Boxing and Unboxing in C#
Garbage Collection in C#
C# - Conditional Statements
C# - Loops
Interfaces in C#
Generics in C#
Collections in C#
C# 8.0 new features
C# Singleton Design Pattern
C# Factory Design Pattern
LINQ in C#
C# - Program to Find Prime Numbers
C# - Fibonacci Sequence
C# - Factorial of a number
C# - Recursive methods
C# - Anonymous Methods
C# - String Methods
C# TDD - XUnit
C# TDD - NUnit
C# Multiton Design Pattern
C# Facade Design Pattern
C# Abstract Factory Design Pattern
C# Decorator Design Pattern
C# Composite Design Pattern

Generics in C#



Generics in C# are a powerful feature that allows you to define classes, methods, delegates, and interfaces with a placeholder for the type of data they store or use. This means you can write more flexible and reusable code without sacrificing type safety or performance. Let' dive in:

Key Features of Generics

  1. Type Safety: Generics enable you to catch type-related errors at compile time rather than at runtime. For example, a generic list can only contain a specific type of items.

    csharp
    List<int> numbers = new List<int>();
    numbers.Add(1); // Works
    numbers.Add("string"); // Compile-time error
    
  2. Code Reusability: Generics allow you to create classes or methods that can work with any data type. This reduces redundancy and the need to write multiple versions of the same code.

    csharp
    public class GenericClass<T>
    {
        public T Data { get; set; }
    }
    
  3. Performance: Using generics avoids boxing and unboxing when working with value types, leading to better performance.

    csharp
    GenericClass<int> intInstance = new GenericClass<int>();
    intInstance.Data = 5; // No boxing involved
    

Common Use Cases

  1. Generic Classes: Classes can be made generic to handle any data type.

    csharp
    public class GenericStack<T>
    {
        private List<T> elements = new List<T>();
    
        public void Push(T item)
        {
            elements.Add(item);
        }
    
        public T Pop()
        {
            if (elements.Count == 0) throw new InvalidOperationException("Stack is empty.");
            T item = elements[elements.Count - 1];
            elements.RemoveAt(elements.Count - 1);
            return item;
        }
    }
    
  2. Generic Methods: Methods can also be defined with generic parameters.

    csharp
    public T Add<T>(T a, T b)
    {
        return (dynamic)a + (dynamic)b; // Dynamic is used here for simplicity, normally not recommended
    }
    
  3. Generic Interfaces: Interfaces can be generic, allowing for more flexible and reusable code design.

    csharp
    public interface IRepository<T>
    {
        void Add(T item);
        T Get(int id);
        void Remove(int id);
    }
    
    public class Repository<T> : IRepository<T>
    {
        private List<T> items = new List<T>();
    
        public void Add(T item) => items.Add(item);
        public T Get(int id) => items[id];
        public void Remove(int id) => items.RemoveAt(id);
    }
    
  4. Generic Delegates: Delegates can also be generic, allowing them to be used with different types of parameters and return types.

    csharp
    public delegate T GenericDelegate<T>(T param);
    

Constraints

Generics in C# can have constraints to specify that the generic type parameter must meet certain criteria.

  • where T : struct: T must be a value type.

  • where T : class: T must be a reference type.

  • where T : new(): T must have a parameterless constructor.

  • where T : SomeBaseClass: T must inherit from SomeBaseClass.

  • where T : ISomeInterface: T must implement ISomeInterface.

csharp
public class GenericClassWithConstraint<T> where T : class, new()
{
    public T Instance { get; set; } = new T();
}
```

Generics are fundamental in C# for creating strongly typed collections, flexible APIs, and reusable libraries. They help maintain performance and type safety, while making the codebase cleaner and more maintainable. If you have specific examples or scenarios in mind, let me know!



All rights reserved | Privacy Policy | Sitemap