The closest to C++ templates in C# is generics - but they're not very close. In particular, you can't use operators like >
between generic type values, because the compiler doesn't know about them (and you can't constrain types based on operators). On the other hand, you can write:
public T GetMax<T>(T lhs, T rhs)
{
return Comparer<T>.Default.Compare(lhs, rhs) > 0 ? lhs : rhs;
}
or
public T GetMax<T>(T lhs, T rhs) where T : IComparable<T>
{
return lhs.CompareTo(rhs) > 0 ? lhs : rhs;
}
Note that the first of these is null-safe; the second isn't.
A full description of generics is well beyond the scope of a Stack Overflow answer; MSDN has some information, or consult your favourite C# book.