Jump to content

How to Create Generic Methods in C#


Linux Hint

Recommended Posts

In C#, a generic method is a method that is declared with a type parameter. Generic methods are very powerful as they can allow you to write a single method that can work with different data types without compromising the type safety.

This also ensures that you do not have to define multiple methods for all the data types that you wish to support.

In this post, we will learn how to work with the generic methods and how to use them in a C# code.

C# Generic Methods

The following code demonstrates the basic syntax of defining a generic method:

public returnType MethodName(GenericType parameter)
{
    // Method body
}

The method is comprised of six main parts:

  1. Public – This defines the method’s access modifier. This is responsible for setting the visibility of the method. The supported values include public, private, protected, and internal.
  2. returnType – The second part is the type of value that is returned by the method. If the method does not return any value, we can use the void keyword.
  3. methodName – The name of the method.
  4. <GenericType> – This acts as a placeholder for the data type.
  5. GenericType parameter – This defines the parameter that the method supports.
  6. Method body – We have the functionality of the method in here.

Basic Usage Example:

The following shows how to define a basic generic method:

public static void Print(T value)
{
    Console.WriteLine($"Value: {value}");
}

In this example, we define a generic method called “Print”. Setting the <T> in the method name indicates that this is a generic method where “T” acts a placeholder for the data type. We can then use this method with any data type as shown in the following example usage:

Print<int>(5);

Print<string>("Hello, World!");

As you can see from the example usage, the value of “T” works with an int and a string.

Working with Constraints

We can also enable the constraints for generic methods which enable the specialized operations on type parameters in the methods.

Consider the following example code:

public static T Max<T>(T value1, T value2) where T : IComparable<T>

{

  return value1.CompareTo(value2) > 0 ? value1 : value2;

}

In this example, we define a generic method that accepts two values and determines the maximum of the two. However, we also include a constraint which tells the C# compiler that this method can only be used with a type that implements the IComparable<T> interface.

Working with Multiple Type Parameters

The following example method shows how to define a generic method that can work with multiple type parameters:

public static void Copy<T, U>(T source, U destination) where U : IList<T>

{
    if (destination == null)
        throw new ArgumentNullException(nameof(destination));

    foreach (var item in source)
    {
        destination.Add(item);
    }
}

In this case, we define a method called “Copy” that copies the items from a collection of type “T” to another collection of type “U”. We also implement a constraint to ensure that the destination collection implements the IList<T> interface.

Conclusion

In this tutorial, we explored the fundamentals of defining and working with generic methods in a C# application.

View the full article

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...