Generics in C# with example

Generics in C# with example


Generics in C# with Example

Generics in C# provide a way to create classes, methods, interfaces, and delegates with a placeholder for the type they operate upon. This feature enhances the flexibility and reusability of code by allowing programmers to create a general solution for various data types. Here we will delve into different aspects of generics in C# with detailed examples.

Types of Generics in C# with Example

Generics in C# can be implemented in classes, methods, interfaces, and delegates. Here’s an example using a generic class and method:

Generic Class Example:

 

public class GenericList<T>
{
    private List<T> internalList = new List<T>();

    public void Add(T item)
    {
        internalList.Add(item);
    }

    public T this[int index]
    {
        get { return internalList[index]; }
    }
}

Usage:

 

var stringList = new GenericList<string>();
stringList.Add("Hello World");
Console.WriteLine(stringList[0]); // Outputs: Hello World

var intList = new GenericList<int>();
intList.Add(1);
Console.WriteLine(intList[0]); // Outputs: 1

C# Generic Method

Generic methods allow the same method logic to work on various data types. Here’s an example:

 

public void Print<T>(T data)
{
    Console.WriteLine(data);
}

Usage:

 

Print("This is a string");
Print(123); // This works with any type

C# Generic Method Return Type

Generic methods can also return values of a generic type:

 

public T CreateNew<T>() where T : new()
{
    return new T();
}

C# Generic Method Where T Multiple Types

You can restrict the types that can be used with a generic method using multiple constraints:

 

public void Add<T>(T item) where T : IComparable, new()
{
    var newItem = new T();
    // Compare and add logic here
}

C# Generic Constraints

Constraints in generics specify the requirements that must be met by the types used as arguments for type parameters. Common constraints include:

  • where T : struct – Type argument must be a value type.
  • where T : class – Type argument must be a reference type.
  • where T : new() – Type argument must have a public parameterless constructor.
  • where T : [base class name] – Type argument must be or derive from the specified base class.
  • where T : [interface name] – Type argument must implement the specified interface.

Example:

 

public class Repository<T> where T : IEntity
{
    public void Save(T item)
    {
        Console.WriteLine($"Saving: {item.Id}");
    }
}

C# Generic Type Parameter

Type parameters in generics act as placeholders for the types specified at compile-time. They enable you to create a variety of functions or classes that work on different types but process them in the same way.

 

public interface IRepository<T>
{
    T FindById(int id);
    void Save(T item);
}

Generics are powerful in that they enable code reuse and type safety without compromising performance. They can significantly simplify many programming tasks by allowing types to be specified later, during the instantiation or implementation of classes and methods.


 

Leave a reply Your email address will not be published. Required fields are marked*

Categories Clouds