Alex Rivera | Logout

Template function in C# - Return Type?

Asked 2010-06-15T21:12:36.993
28

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?

Edit
Report

1 Answer

5

Your code would become something like this:

public T GetMax<T>(T a, T b) where T : IComparable<T>
{
    return a.CompareTo(b) > 0 ? a : b;
}
answered 2010-06-15T21:18:48.447

Your Answer