Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Generic Methods in C#

Introduction to Generics

Generics in C# allow you to define classes, interfaces, and methods with a placeholder for the type of data they store or use. This enables type safety and reusability without the overhead of multiple type-specific implementations. Instead of writing multiple versions of the same method or class to handle different data types, you can define a single generic version.

What are Generic Methods?

Generic methods are methods that are written with a generic type parameter. These methods can be defined in a generic class or in a normal class. The type parameter can be replaced with any data type when the method is called. This allows the method to be type-safe and reusable.

Defining a Generic Method

To define a generic method, you add a type parameter to the method signature. The type parameter is specified in angle brackets after the method name. Here’s the basic syntax:

public void MethodName<T>(T parameter) {
    // Method body
}
                

Example of a Generic Method

Let’s look at an example of a generic method that simply prints the passed parameter:

using System;

public class GenericMethodExample {
    public void Print<T>(T item) {
        Console.WriteLine(item);
    }
}

public class Program {
    public static void Main() {
        GenericMethodExample example = new GenericMethodExample();
        example.Print<int>(123);      // Works with an int
        example.Print<string>("Hello"); // Works with a string
        example.Print<double>(12.34);  // Works with a double
    }
}
                

When this code is executed, it will output:

123
Hello
12.34

Benefits of Using Generic Methods

Using generic methods provides several benefits:

  • Type Safety: Generic methods ensure that you are working with the correct data type.
  • Code Reusability: You can write a method once and use it with different data types without rewriting the method.
  • Performance: Generics reduce the need for boxing/unboxing, thus improving performance.

Constraints on Generic Methods

In some cases, you might want to restrict the types that can be used with your generic method. This is where constraints come in. Constraints specify the requirements that a type must meet to be used as a type argument for a generic method. For example:

public void MethodName<T>(T parameter) where T : IComparable {
    // Method body that requires T to implement IComparable
}
                

Here’s an example of a generic method with a constraint:

using System;

public class GenericMethodExample {
    public void CompareToZero<T>(T value) where T : IComparable {
        if (value.CompareTo(default(T)) > 0) {
            Console.WriteLine($"{value} is greater than zero.");
        } else {
            Console.WriteLine($"{value} is less than or equal to zero.");
        }
    }
}

public class Program {
    public static void Main() {
        GenericMethodExample example = new GenericMethodExample();
        example.CompareToZero(5);       // Works with an int
        example.CompareToZero(0);       // Works with an int
        example.CompareToZero(-5);      // Works with an int
        example.CompareToZero(5.5);     // Works with a double
    }
}
                

When this code is executed, it will output:

5 is greater than zero.
0 is less than or equal to zero.
-5 is less than or equal to zero.
5.5 is greater than zero.

Conclusion

Generic methods are a powerful feature in C# that allow you to write flexible, reusable, and type-safe methods. By using generic methods, you can avoid code duplication and ensure that your methods work with a wide range of data types. Constraints further enhance the utility of generic methods by ensuring that the types used meet certain requirements.