You Don’t Have to Write a Generic Class to Use Generic Methods in C#

We can create generic classes such as:

class ThingWriter<T>
{
    public void Write(T thing)
    {
        Console.WriteLine(thing);
    }
}

Here we’re defining a generic class, then using the type T as a method parameter in the Write method. To use this class we’d write something like:

var w = new ThingWriter<int>();

w.Write(42);

We don’t however have to be working in a generic class to make use of generic methods.

The following code shows how we could remove the generic from the class and just create a generic method instead:

class ThingWriter
{
    public void Write<T>(T thing)
    {
        Console.WriteLine(thing);
    }
}

To call this generic method  we’d write:

var w = new ThingWriter();

w.Write<int>(42);

Or by taking advantage of generic type inference, we can let the compiler figure the type out for us from the fact that the parameter we’re passing is an int:

var w = new ThingWriter();

w.Write(42);

 

(For more C# tips check out my Pluralsight courses: C# Tips and Traps and C# Tips and Traps 2)

SHARE:

Add comment

Loading