Generics in C# are a feature that allow you to write classes, interfaces, and methods that can work with any data type. With generics, you can create a class or method that operates on a type that is only specified at runtime, rather than being hard-coded at design time.
Using generics, you can create highly reusable code that can be used with multiple types, without the need to write separate versions of the same code for each type. This can make your code more flexible and easier to maintain.
Here's an example of a generic class in C#:
csharppublic class Stack<T>
{
private T[] items;
private int top;
public Stack(int size)
{
items = new T[size];
top = -1;
}
public void Push(T item)
{
items[++top] = item;
}
public T Pop()
{
return items[top--];
}
}
In this example, the Stack
class is defined with a type parameter T
. This means that you can create an instance of the Stack
class for any data type. For example, you can create a Stack<int>
for storing integers, or a Stack<string>
for storing strings.
Comments
Post a Comment