Generics in C#

 Generics in C#


Generics allow a program to define type-safe classes, structures, methods, and interfaces that can work with any data type. The generic types are specified using type parameters. Here's an example code that demonstrates how to define a generic class:


class Stack<T>

{

    private T[] items;

    private int top;


    public Stack()

    {

        items = new T[100];

        top = -1;

    }


    public void Push(T item)

    {

        items[++top] = item;

    }


    public T Pop()

    {

        return items[top--];

    }

}


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

intStack.Push(10);

intStack.Push(20);

Console.WriteLine(intStack.Pop());  // prints 20


Stack<string> stringStack = new Stack<string>();

stringStack.Push("hello");

stringStack.Push("world");

Console.WriteLine(stringStack.Pop());  // prints "world"

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...