How can I create a function that will have a dynamic return type based on the parameter type?
Like
protected DynamicType Test(DynamicType type)
{
retur
Whilst the accepted answer is good, it has been over two years since it was written, so, I should add that you can use:
protected dynamic methodname(dynamic input)
{
return input;
}
Input will be returned as the same type, and you do not need to call the method as a generic.
Reference:
https://msdn.microsoft.com/en-us/library/dd264736.aspx
C# is not a dynamic language. To tackle this problem in C# you can return a generic object and typecast later to whatever you think the value should be -- not recommended. You can also return an interface, this way you don't really care about a specific class instance. As others have pointed out you can also use generics. It really depends on what you need / want to do inside the body of the function since all the methods above have their own limitations.
You'd have to use generics for this. For example,
protected T Test<T>(T parameter)
{
}
In this example, the '<T>
' tells the compiler that it represents the name of a type, but you don't know what that is in the context of creating this function. So you'd end up calling it like...
int foo;
int bar = Test<int>(foo);
Actually, assuming that you have a known set of parameters and return types, it could be handled with simple overloading:
protected int Test(string p) { ... }
protected string Test(DateTime p ) { .... }
Then you need use generics.
protected T Test(T type) {
return type;
}