C# Interview Question #107
What is a generic method, and how does type inference work?
Types, Equality, Immutability & Internals Senior Advanced
Quick Interview Answer
A generic method declares one or more type parameters independently of whether the containing class is generic.
Detailed Explanation
A generic method declares one or more type parameters independently of whether the containing class is generic.
The compiler can often infer generic type arguments from the arguments passed to the method. When inference is not possible or when clarity is needed, the type argument can be supplied explicitly.
Generic methods provide reusable, strongly typed algorithms without requiring separate implementations for each data type.
Code Example
public static T MaxValue<T>(T a, T b)
where T : IComparable<T>
{
return a.CompareTo(b) >= 0 ? a : b;
}
int max = MaxValue(10, 20);
string text = MaxValue<string>("A", "B");