Functions

C# Generic Methods

Generic Methods

C# generic methods use <T> for type-safe polymorphism.

Introduction to C# Generic Methods

C# generic methods allow you to define a method with a placeholder for the data type, specified with <T>. This approach enables methods to operate on different data types while ensuring type safety. By using generics, you can write flexible, reusable, and maintainable code.

Defining a Generic Method

When defining a generic method, you specify a type parameter in angle brackets <> after the method name. This type parameter can then be used within the method. Here's the syntax:

In the above example, T is a placeholder for the actual data type that will be used when the method is called. The Swap method swaps the values of two variables of the same type.

Calling a Generic Method

When calling a generic method, the type parameter is usually inferred by the compiler. However, you can also explicitly specify the type. Here's how you can use the Swap method:

In this example, the Swap method is used to swap integers as well as strings. The compiler infers the type from the arguments passed to the method.

Benefits of Using Generic Methods

Generic methods provide several benefits:

  • Code Reusability: Write a method once and use it with different data types.
  • Type Safety: Ensure type checks at compile time, reducing runtime errors.
  • Performance: Reduce the need for boxing/unboxing and casting, enhancing performance.

Constraints in Generic Methods

Sometimes, you might want to restrict the types that can be used with a generic method. You can do this using constraints. For example, you can ensure that a type implements a specific interface or is a subclass of a particular class. Here's how you can apply constraints:

In this example, the Display method is constrained to types that implement the IComparable interface, ensuring that the method can only be called with comparable types.