VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/generic-methods-in-c/

⇱ Generic Methods in C# - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Generic Methods in C#

Last Updated : 20 Apr, 2026

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


Output
Value: 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


Output
x = 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.


Output
First: 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

  1. Type Safety: Errors are caught at compile time instead of runtime.
  2. Code Reusability: One method works with multiple data types.
  3. Performance: Avoids boxing/unboxing for value types.
  4. Flexibility: Can define multiple type parameters for different scenarios.
Comment
Article Tags:
Article Tags:

Explore