C# Tutorial

C# String

C# Array

C# Flow Control

C# Class and Object

C# Inheritance

C# Interface

C# Collection

C# Generic

C# File I/O

C# Delegate and Event

C# Exception

C# Process and Thread

C# ADO.NET Database Operations

C# Generic Methods

In this tutorial, we will explore generic methods in C#. Generic methods are methods that have one or more type parameters, allowing you to create more flexible, reusable, and type-safe code.

  • Defining a Generic Method

To define a generic method, you include the type parameters inside angle brackets <T> after the method name, where T is a placeholder for the actual type you will use later.

Here's a simple example of a generic method called PrintArray:

public static void PrintArray<T>(T[] array)
{
    foreach (T item in array)
    {
        Console.Write(item + " ");
    }
    Console.WriteLine();
}

In this example, T is a type parameter that represents the type of the elements in the array parameter.

  • Calling a Generic Method

When calling a generic method, the compiler usually infers the type parameters based on the method arguments. For example, you can call the PrintArray method with different types of arrays:

int[] intArray = { 1, 2, 3 };
string[] stringArray = { "Hello", "World" };

PrintArray(intArray); // Output: 1 2 3
PrintArray(stringArray); // Output: Hello World

If the compiler cannot infer the type parameters, you can explicitly specify them using angle brackets:

PrintArray<int>(intArray);
  • Adding Constraints to Type Parameters

You can add constraints to type parameters to restrict the types that can be used with the generic method. Constraints are specified using the where keyword followed by the type parameter, a colon, and the constraint.

For example, you can define a generic method to compare two objects of a type that implements IComparable<T>:

public static T Max<T>(T a, T b) where T : IComparable<T>
{
    return a.CompareTo(b) > 0 ? a : b;
}

In this example, the constraint where T : IComparable<T> ensures that the type T implements the IComparable<T> interface, allowing you to call the CompareTo method.

You can use the Max method with types that implement IComparable<T>:

int maxInt = Max(5, 10); // 10
string maxString = Max("apple", "banana"); // "banana"
  • Generic Methods in Generic Classes

You can define generic methods within generic classes. The method's type parameters can be different from or extend the class's type parameters. Here's an example of a generic method inside a generic class:

public class Container<T>
{
    private List<T> _items = new List<T>();

    public void Add(T item)
    {
        _items.Add(item);
    }

    public void AddRange<U>(IEnumerable<U> items) where U : T
    {
        _items.AddRange(items);
    }
}

In this example, the AddRange method has a different type parameter U that is constrained to be a subtype of T. This allows you to add a range of items to the container as long as they are of the same type or a derived type of T.

This tutorial demonstrates the basics of defining and using generic methods in C#. Generics are a powerful feature that enables you to create more flexible and reusable code, while preserving type safety.

  1. How to define generic methods in C#:

    • Description: Generic methods are methods that can operate on different data types by using type parameters.
    • Code:
      public class GenericMethods
      {
          public T Display<T>(T value)
          {
              Console.WriteLine(value);
              return value;
          }
      }
      
  2. C# generic method example:

    • Description: An example showcasing the use of a generic method to display and return a value of any data type.
    • Code:
      class Program
      {
          static void Main()
          {
              GenericMethods genericMethods = new GenericMethods();
              int intValue = genericMethods.Display(42);
              string stringValue = genericMethods.Display("C# Generics");
          }
      }
      
  3. Type inference in C# generic methods:

    • Description: Type inference allows the compiler to deduce the type based on the provided arguments, making method calls concise.
    • Code:
      var inferredValue = genericMethods.Display("Inferred Type");
      
  4. C# generic method constraints:

    • Description: Constraints restrict the types that can be used with a generic method, ensuring certain conditions are met.
    • Code:
      public T CompareTo<T>(T value) where T : IComparable<T>
      {
          // Implementation for comparing values
      }
      
  5. Overloading with generic methods in C#:

    • Description: Generic methods can be overloaded, providing different implementations for specific scenarios.
    • Code:
      public T Sum<T>(T a, T b)
      {
          // Implementation for summing values of the same type
      }
      
      public string Sum(string a, string b)
      {
          // Implementation for concatenating strings
      }
      
  6. C# extension methods with generics:

    • Description: Extension methods can be generic, allowing you to extend existing types with new functionality.
    • Code:
      public static class StringExtensions
      {
          public static bool IsNullOrEmpty<T>(this T input)
          {
              // Implementation for checking if the input is null or empty
          }
      }
      
  7. Generic method with multiple type parameters in C#:

    • Description: Generic methods can have more than one type parameter to handle scenarios requiring multiple data types.
    • Code:
      public void DisplayPair<TFirst, TSecond>(TFirst first, TSecond second)
      {
          Console.WriteLine($"{first}, {second}");
      }