How to Create Generic Class in C# - Simple Guide
In C#, you create a generic class by adding a type parameter inside angle brackets after the class name, like
class MyClass<T>. This allows the class to work with any data type specified when you create an object of that class.Syntax
To define a generic class, use angle brackets <> with a type parameter after the class name. The type parameter is a placeholder for any data type.
- T: The type parameter name (can be any valid identifier).
- class MyClass<T>: Declares a generic class named
MyClasswith type parameterT. - Inside the class, you can use
Tas a type for fields, properties, methods, etc.
csharp
public class MyClass<T> { public T Value { get; set; } public void Display() { System.Console.WriteLine($"Value: {Value}"); } }
Example
This example shows a generic class Box<T> that stores a value of any type and prints it. We create two objects: one with an int and one with a string.
csharp
using System; public class Box<T> { public T Content { get; set; } public void ShowContent() { Console.WriteLine($"Content: {Content}"); } } class Program { static void Main() { Box<int> intBox = new Box<int> { Content = 123 }; intBox.ShowContent(); Box<string> strBox = new Box<string> { Content = "Hello" }; strBox.ShowContent(); } }
Output
Content: 123
Content: Hello
Common Pitfalls
- Forgetting to specify the type argument when creating an object, e.g., writing
new Box()instead ofnew Box<int>(). - Using multiple type parameters but mixing up their order or names.
- Trying to use operators (like
+) directly on generic types without constraints. - Not adding constraints when you need specific capabilities (like requiring a type to be a class or have a parameterless constructor).
csharp
/* Wrong: Missing type argument */ // Box myBox = new Box(); // Error: The type arguments for 'Box<T>' cannot be inferred /* Right: Specify type argument */ Box<int> myBox = new Box<int>();
Quick Reference
Summary tips for generic classes in C#:
- Use
<T>to declare a generic type parameter. - Specify the type when creating an instance, e.g.,
new MyClass<int>(). - Add constraints with
whereif needed, e.g.,where T : class. - Generic classes improve code reuse and type safety.
Key Takeaways
Define a generic class by adding a type parameter in angle brackets after the class name.
Use the type parameter inside the class to create flexible, reusable code.
Always specify the type argument when creating an instance of a generic class.
Add constraints to type parameters if you need specific type features.
Generic classes help avoid code duplication and improve type safety.