Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template function in C# - Return Type?

Tags:

It seems that c# does not support c++ like templates. For example

template <class myType>
myType GetMax (myType a, myType b) {
 return (a>b?a:b);
}

I want my function to have return type based on its parameters, how can i achieve this in c#? How to use templates in C#

EDIT: Can i use object and getType for the almost same purpose?

like image 771
SMUsamaShah Avatar asked Jun 15 '10 21:06

SMUsamaShah


2 Answers

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.

like image 69
Jon Skeet Avatar answered Sep 20 '22 09:09

Jon Skeet


Generics in C# are not as powerful as templates in C++. What you want to do does not work in C#.

A hack/workaround for your situation is

public T GetMax<T>(T a, T b) where T: IComparable {
    if(a.CompareTo(b) > 0) {
        return a;
    }
    return b;
}
like image 45
Matt Greer Avatar answered Sep 21 '22 09:09

Matt Greer