C # - Function return type is the same as parameter

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

Here is 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 a parameter and return the same class.

Thanks!

+6
source share
1 answer

You need a common 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 such as Equals, ToString, etc. You can add a where constraint to the generic method to suggest that the parameter is something concrete, like a class or structure.

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

Although there is a good chance that you can really just use a base class or interface to handle multiple types the same way. When using the general method, you will quickly understand if you cannot do what you can do with this template. If your restriction leads you to limit your general method to only working with a particular type of interface, you probably just want this method to be part of the interface.

+18
source

Source: https://habr.com/ru/post/956190/


All Articles