Skip to main content

How to Write a Generic Method in C#

· 5 min read
Jagdish Kumawat
Founder @ Dewiride

A method that returns the first item of an array works the same for numbers, names or anything else. Instead of one copy per type, C# lets you write it once with a type parameter, T, that the caller fills in: First<int>, First<string>, or left to the compiler to work out.

Syntax​

Syntax
<ReturnType> <Name><T>(<parameters that use T>)
{
<statements that use T>
}
PartWhat it does
<T> after the nameDeclares a type parameter: a placeholder for a type the caller chooses. T is the usual name.
<parameters that use T>Parameters typed with T, such as T[] items.
<ReturnType>Can be T too, so the method returns the caller's type.
<Name><int>(...)A call that fills in T explicitly. Leave out <int> and the compiler infers it from the arguments.

Microsoft's generic methods guide: "A generic method is a method that is declared with type parameters". And: "You can also omit the type argument and the compiler will infer it."

The Example​

A First<T> method returns the first item of an array of any type. The program calls it for an int array and a string array with the type written out, and once without it.

Prerequisites​

  • The .NET 10 SDK or newer, which runs a single .cs file with dotnet run. This guide uses .NET SDK 10.0.404.

Step 1: Write the Code​

Create a file named main.cs in an empty folder:

main.cs, which prints First of int for 3, 4 and 5, First of string for Leo and Maya, and First for inferred without a type argument, where the static generic First method takes a T array and returns its first item.

main.cs
Console.WriteLine(First<int>([3, 4, 5]));
Console.WriteLine(First<string>(["Leo", "Maya"]));
Console.WriteLine(First(["inferred"]));

static T First<T>(T[] items) => items[0];

In First<int>, every T in the method becomes int: it takes an int[] and returns an int. In the last call, the array holds a string, so the compiler infers T is string.

Step 2: Run It​

Terminal
dotnet run main.cs
Output
3
Leo
inferred

A zsh terminal where dotnet run main.cs prints 3, Leo and inferred.

One method handled numbers and strings, with and without the type written out. The command is the same in zsh, bash and PowerShell.

What Happens When the Types Don't Agree​

With T set to int, the method accepts only int values:

main.cs
Console.WriteLine(First<int>(["Leo"]));

static T First<T>(T[] items) => items[0];
Output
/Users/you/demo/main.cs(1,31): error CS0029: Cannot implicitly convert type 'string' to 'int'

The build failed. Fix the build errors and run again.

The type parameter keeps the method type-safe: a string can't sneak into an int array.

What Happens When There's Nothing to Infer From​

An empty collection expression gives the compiler no clue about T:

main.cs
Console.WriteLine(First([]));

static T First<T>(T[] items) => items[0];
Output
/Users/you/demo/main.cs(1,19): error CS0411: The type arguments for method 'First<T>(T[])' cannot be inferred from the usage. Try specifying the type arguments explicitly.
/Users/you/demo/main.cs(3,10): warning CS8321: The local function 'First' is declared but never used

The build failed. Fix the build errors and run again.

Write the type, as the message suggests: First<int>([]). The warning is a side effect: because the only call failed, the compiler counts the method as unused.

Common Mistakes​

MistakeWhat happensDo this instead
Passing values of another type than the one written in <...>error CS0029: Cannot implicitly convert type 'string' to 'int'Match the type argument to the values, or leave it out
Calling with nothing the compiler can infer T fromerror CS0411: The type arguments for method 'First<T>(T[])' cannot be inferred from the usage.Write the type argument: First<int>(...)
Writing three copies of a method for three typesThe copies drift apart over timeWrite one generic method

Troubleshooting​

SymptomLikely causeFix
CS0411The arguments don't reveal TAdd the type argument explicitly
CS0029 inside a generic callThe values don't fit the type argumentChange one or the other

FAQ​

When can the compiler infer T?​

From the arguments only. The guide: "The compiler can infer the type parameters based on the method arguments you pass in; it cannot infer the type parameters only from a constraint or return value. Therefore type inference does not work with methods that have no parameters."

Where have I seen generic methods before?​

In .NET itself. configuration.Get<string[]>() and LINQ methods such as Select are generic methods: the type in angle brackets, written or inferred, tells them what to work with.

Conclusion​

Add <T> after a method's name and use T for its parameters and return type, and the method works for any type the caller chooses. Write the type argument, as in First<int>(...), or let the compiler infer it from the arguments.

Additional Resources​