A generic method is a method that has one or more type parameters defined within angle brackets (< >) after the method name. These parameters are specified when the method is called. Generic methods are useful when the logic of a method is the same for multiple data types, such as swapping values, comparing items or printing data.
- Generic methods can exist inside regular classes or generic classes.
- If the compiler can infer the type from arguments, you don’t need to explicitly specify it (e.g., Display("Hello") instead of Display<string>("Hello")).
- Generic methods are widely used in LINQ and collection utility methods.
Syntax
ReturnType MethodName<T>(T param){
// method body
}
- T: Type parameter (placeholder for actual type).
- The type is specified when calling the method.
Type parameters are specified at method call, but sometimes the compiler infers them automatically.
Example: Simple Generic Method
OutputValue: 100
Value: GeeksForGeeks
Value: 99.99
Explanation:
- Display<int>(100): Here T is replaced by int.
- Display<string>("GeeksForGeeks"): Here T is replaced by string.
- Display<double>(99.99): Here T is replaced by double.
Example: Generic Method for Swapping Values
Outputx = 20, y = 10
s1 = World, s2 = Hello
Explanation:
- The Swap<T> method works for both integers and strings without needing separate implementations.
- ref ensures that the values are swapped in place.
Generic Method with Multiple Type Parameters
A generic method can also define more than one type parameter.
OutputFirst: 1, Second: One
First: Pi, Second: 3.14
Explanation: The method defines multiple type parameters (T1, T2) to work with different data types in a single method. Each type parameter represents a different data type passed during method invocation. This allows the method to handle multiple values of different types without creating separate methods.
Advantages
- Type Safety: Errors are caught at compile time instead of runtime.
- Code Reusability: One method works with multiple data types.
- Performance: Avoids boxing/unboxing for value types.
- Flexibility: Can define multiple type parameters for different scenarios.