Generic Methods
Type parameters on methods.
Generic Methods is a free C# Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the C# Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Are Generic Methods?
A generic method declares one or more type parameters of its own, written in angle brackets after the method name. The same method body then works for many types without casting or duplication.
Type parameters are placeholders like T. The compiler substitutes the real type at the call site, keeping everything strongly typed.
void Print<T>(T value)
{
Console.WriteLine(value);
}Declaring a Type Parameter
The type parameter list <T> sits between the method name and the parameter list. You can use T as a parameter type, a return type, or a local variable type inside the body.
By convention single type parameters are named T; descriptive names like TKey are also common.
T Echo<T>(T input)
{
return input;
}Calling With Type Inference
You usually do not specify the type argument explicitly. The compiler infers T from the arguments you pass.
Here Echo(42) infers T = int, and Echo("hi") infers T = string. Type inference keeps generic calls clean and readable.
using System;
class Program
{
static T Echo<T>(T input) => input;
static void Main()
{
Console.WriteLine(Echo(42));
Console.WriteLine(Echo("hi"));
}
}Explicit Type Arguments
When inference cannot determine the type, or when you want to be explicit, supply the type argument in angle brackets at the call site.
This is required when no argument carries the type, for example a method whose T appears only in the return type.
T Create<T>() where T : new() => new T();
// call:
var list = Create<int>();Multiple Type Parameters
A generic method can declare several type parameters separated by commas. Each is inferred or supplied independently.
A classic example is a swap or a pair builder that mixes two distinct types.
(TSecond, TFirst) Flip<TFirst, TSecond>(TFirst a, TSecond b)
{
return (b, a);
}A Generic Swap
Generic methods shine for utilities that ignore the concrete type. A swap reorders two values of any matching type.
The ref keyword lets the method modify the caller's variables in place.
using System;
class Program
{
static void Swap<T>(ref T a, ref T b)
{
T temp = a;
a = b;
b = temp;
}
static void Main()
{
int x = 1, y = 2;
Swap(ref x, ref y);
Console.WriteLine($"{x} {y}");
}
}Constraints on Method Parameters
A generic method can restrict its type parameters with a where clause. Constraints tell the compiler what operations are allowed on T.
Below, where T : IComparable<T> lets the body call CompareTo safely.
T Max<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) >= 0 ? a : b;
}Generic Methods in Non-Generic Classes
A class does not need to be generic to contain generic methods. Static utility classes commonly hold them.
This keeps general-purpose helpers grouped without forcing the whole class to carry a type parameter.
static class Util
{
public static T First<T>(T[] items) => items[0];
}Inference From Arrays
Type inference works through array and collection arguments too. Passing an int[] infers T = int automatically.
This makes generic algorithms feel like built-in language features.
using System;
class Program
{
static T First<T>(T[] items) => items[0];
static void Main()
{
int[] nums = { 10, 20, 30 };
Console.WriteLine(First(nums));
}
}Why Not Just Use object?
Before generics, code used object and casts. That loses type safety and boxes value types, hurting performance.
Generic methods avoid boxing for value types and catch type mistakes at compile time instead of throwing at runtime.
// Unsafe: needs a cast and can fail at runtime
object Echo(object o) => o;
int n = (int)Echo(5);Returning Different Types
The return type can itself be generic, letting one method shape its output to the caller. default(T) yields the zero value for value types or null for reference types.
This is handy for safe fallbacks when no value is available.
T OrDefault<T>(bool ok, T value)
{
return ok ? value : default(T);
}Quick Check
Test your understanding of generic methods.
Recap
Generic methods declare their own type parameters in angle brackets after the name. The compiler usually infers the type from arguments, but you can supply it explicitly.
They preserve type safety, avoid boxing, and can carry where constraints. You can place them in any class, generic or not.
Frequently asked questions
Is the “Generic Methods” lesson free?
Yes — the full text of “Generic Methods” is free to read here on the web, and the C# Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the C# Academy course, upgrade to CoddyKit PRO.
What will I learn in “Generic Methods”?
Type parameters on methods. You practise C# Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start C# Academy?
No prior experience is required. C# Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Generic Methods” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this C# Academy lesson?
Yes. Every C# Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Generic Methods
- Generic Classes
- where Constraints
- Generic Interfaces