Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Return type of a function is the same a the one of a parameter

Tags:

c#

parameters

I was wondering if it's possible for a function to return a value of type specified in a parameter in C#.

Here what I want to do:

public ReturnValueUndefined function(undefinedType value)
{
    return value;
}

I want to use this because I want my function to take any class as parameter and return the same class.

Thank you!

like image 595
Adrien Neveu Avatar asked Oct 17 '13 17:10

Adrien Neveu


1 Answers

You want a generic function.

public T YourFunctionName<T>(T value)
{
    return value;
}

Keep in mind that the compiler can only assume that T is an object so you can only perform basic operations like Equals, ToString, etc. You can add a where constraint to the generic method to assume that the parameter is something concrete like a class or a structure.

public T YourFunctionName<T>(T value) where T : class
{
    return value;
}

Although there is a good chance that you might actually just want to use a base class or interface to treat multiple types the same. When using a generic method you will realize quickly if you can't do what you may want to do with that pattern. If your constraint brings you to the point where you must constrain your generic method to only work on a specific interface type then you probably just want the method to be part of the interface anyway.

like image 59
Trevor Elliott Avatar answered Sep 27 '22 17:09

Trevor Elliott