Saturday, May 13, 2023

What is generic in c#?| Generic in c#| c# generic

 What is generic in c#?


In C#, generics provide a way to create type-safe and reusable code by parameterizing classes, methods, and interfaces with one or more type parameters. This allows a single generic type or method to work with multiple types of data, without the need for casting or boxing/unboxing.


Generics were introduced in C# 2.0 and are implemented using type parameters, which are specified between angle brackets (`<` and `>`) after the name of the class, method, or interface. For example, the following code defines a generic class `Stack<T>` that can hold elements of any type `T`:



public class Stack<T>

{

    private T[] elements;

    private int top = -1;


    public void Push(T item)

    {

        elements[++top] = item;

    }


    public T Pop()

    {

        return elements[top--];

    }

}



In this example, the type parameter `T` is used to declare a private array of elements and to specify the types of the input parameter and the return value of the `Push` and `Pop` methods.


To use the `Stack<T>` class, you can instantiate it with a specific type, such as `int`, `string`, or `object`, as follows:



Stack<int> stackOfInts = new Stack<int>();

stackOfInts.Push(1);

stackOfInts.Push(2);

int x = stackOfInts.Pop();



In this example, the `stackOfInts` variable is of type `Stack<int>`, which means that it can only hold integers. The `Push` method adds an integer to the stack, and the `Pop` method removes and returns the top element of the stack.


Generics can also be used with methods and interfaces, and can be constrained with type constraints to restrict the types that can be used as type parameters. Overall, generics provide a powerful and flexible way to write reusable and type-safe code in C#.

No comments:

Post a Comment

If you have any query kindly let me know.

Blazor drawback| drawback of blazor| Disadvantage of blazor in c#

  Blazor drawback| drawback of blazor| Disadvantage of blazor in c# While Blazor offers many advantages, it also has a few drawbacks to cons...