How to Create Generic Method in C# - Simple Guide
In C#, you create a generic method by adding a type parameter in angle brackets
<T> after the method name. This allows the method to work with any data type specified when calling it, making your code reusable and type-safe.Syntax
A generic method in C# uses a type parameter inside angle brackets <T> after the method name. The type parameter T acts as a placeholder for any data type you want to use when calling the method.
Here is what each part means:
- public: The method can be accessed from outside the class.
- void: The method does not return a value (can be changed to any return type).
- MethodName<T>: The method name followed by the generic type parameter
T. - (T parameter): The method takes a parameter of type
T.
csharp
public void MethodName<T>(T parameter) { // Method body using parameter of type T }
Example
This example shows a generic method that prints any type of value passed to it. It works with int, string, or any other type.
csharp
using System; class Program { public static void PrintValue<T>(T value) { Console.WriteLine($"Value: {value}"); } static void Main() { PrintValue<int>(123); // Prints an integer PrintValue<string>("Hello"); // Prints a string PrintValue<double>(3.14); // Prints a double } }
Output
Value: 123
Value: Hello
Value: 3.14
Common Pitfalls
Some common mistakes when creating generic methods include:
- Forgetting to add the
<T>after the method name. - Using a type parameter inside the method without declaring it.
- Trying to use operations on
Tthat are not supported for all types (like arithmetic without constraints).
Always declare the generic type parameter and be careful with operations that require specific type capabilities.
csharp
/* Wrong: Missing <T> after method name */ // public void ShowValue(T value) { Console.WriteLine(value); } /* Right: Declare generic type parameter <T> */ public void ShowValue<T>(T value) { Console.WriteLine(value); }
Quick Reference
| Concept | Description |
|---|---|
| Generic type parameter placeholder | |
| MethodName | Method name with generic type |
| T parameter | Parameter of generic type |
| Constraints | Optional limits on types (e.g., where T : class) |
| Usage | Call method with specific type: MethodName |
Key Takeaways
Add after the method name to declare a generic method.
Use the generic type T as a placeholder for any data type in parameters or return type.
Call generic methods by specifying the type in angle brackets, like MethodName(value).
Avoid using operations on T that are not valid for all types unless you add constraints.
Generic methods make your code reusable and type-safe for different data types.