Generic Programming in C# : Generics

Mannan Ul Haq
0

Generics in C#:

Generics are a powerful feature in C# that allows you to define type-safe data structures, without committing to actual data types. This results in a high level of code reuse and performance. Generics are most frequently used with collections and the methods that operate on them.

The basic syntax to define generics involves using angle brackets `<>` and place holders (like `T`), which act as a stand-in for any data type.

public class GenericClass<T> { ... }
public void GenericMethod<T>(T parameter) { ... }

Here, `T` is the type parameter, which will be replaced by the actual data type when an instance of `GenericClass` is created or `GenericMethod` is called.

Generic Methods:

Here's an example of a simple generic method:

static void Display<T>(T item)
{
    Console.WriteLine(item);
}

In this case, `T` is a placeholder for any type. This method can be used to display an item of any type:

Display<int>(5); // output: 5
Display<string>("Hello World"); // output: Hello World

Generic Classes:

A generic class can be defined in a similar way to a method. Here's an example:

class MyGenericClass<T>
{
    private T item;

    public void UpdateItem(T newItem)
    {
        item = newItem;
    }

    public T GetItem()
    {
        return item;
    }
}

You can create an instance of this class using any data type:

MyGenericClass<int> myInt = new MyGenericClass<int>();
myInt.UpdateItem(5);
Console.WriteLine(myInt.GetItem()); // output: 5

MyGenericClass<string> myString = new MyGenericClass<string>();
myString.UpdateItem("Hello");
Console.WriteLine(myString.GetItem()); // output: Hello

Generic Class Methods:

You can also create generic methods within non-generic classes:

class MyClass
{
    public T Display<T>(T value)
    {
        Console.WriteLine(value);
        return value;
    }
}

You can call Display with any type:

MyClass myObject = new MyClass();
myObject.Display<int>(10);       // Output: 10
myObject.Display<string>("Hello");  // Output: Hello

Multiple Generic Arguments:

Both generic methods and classes can use multiple type parameters. Here is an example with a method:

public void Display<T1, T2>(T1 value1, T2 value2)
{
    Console.WriteLine(value1);
    Console.WriteLine(value2);
}

You can call Display with any types:

Display<int, string>(5, "Hello");  // Output: 5 Hello

Tags

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !