C# Generics
Generics are a powerful feature of C# that allow you to write classes and methods that work with any data type. Generics provide type safety, code reuse, and efficiency. In this tutorial, we'll discuss how to use generics in C#.
Syntax
The syntax for using generics in C# is as follows:
public class MyClass<T> {
// code
}
public void MyMethod<T>(T arg) {
// code
}
In the above examples, T is a type parameter that can represent any data type.
Example
Let's say we want to create a generic class that can work with any data type. Here's how we can implement it:
public class MyGenericClass<T> {
private T[] arr;
public MyGenericClass(int size) {
arr = new T[size];
}
public void SetItem(int index, T value) {
arr[index] = value;
}
public T GetItem(int index) {
return arr[index];
}
}
We can now create an instance of the class and use it with any data type:
MyGenericClass<int> intClass = new MyGenericClass<int>(3);
intClass.SetItem(0, 10);
intClass.SetItem(1, 20);
intClass.SetItem(2, 30);
Console.WriteLine(intClass.GetItem(0)); // Output: 10
MyGenericClass<string> stringClass = new MyGenericClass<string>(2);
stringClass.SetItem(0, "Hello");
stringClass.SetItem(1, "World");
Console.WriteLine(stringClass.GetItem(1)); // Output: World
Output
When we run the example code above, the output will be:
10
World
This is because we created two instances of the MyGenericClass class - one for integers and one for strings - and set and retrieved values using the SetItem and GetItem methods.
Explanation
In the example above, we defined a generic class called MyGenericClass that can work with any data type. We used a type parameter T to represent the data type. We can create an instance of this class for any data type, and set and retrieve values using the SetItem and GetItem methods.
Use
Generics are useful when you want to write classes and methods that work with any data type. They allow you to write code that is reusable and efficient while maintaining type safety.
Important Points
- Generics provide type safety by ensuring that the data types used with a class or method are the correct type.
- You can use multiple type parameters to define more complex generic classes and methods.
- Generics can improve the performance of your code by reducing the need for casting and boxing/unboxing.
Summary
In this tutorial, we discussed how to use generics in C#. We covered the syntax, example, output, explanation, use, and important points of generics in C#. With this knowledge, you can now use generics in your C# code to create classes and methods that work with any data type.