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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With