How can I create a function that will have a dynamic return type based on the parameter type?
Like
protected DynamicType Test(DynamicType type) { return ; }
Yes there are ways by which you can deliver different objects on run time and dynamic is one of those solution. Today, we will understand how to use dynamic keyword to return a whole different object on runtime. You can even change the return type based on your input.
Dynamic data types are dynamic in nature and don't require initialization at the time of declaration. It also means that a dynamic type does not have a predefined type and can be used to store any type of data. We can define this data type using the keyword “dynamic" in our code.
A dynamic type variables are defined using the dynamic keyword. Example: dynamic Variable. dynamic MyDynamicVar = 1; The compiler compiles dynamic types into object types in most cases. However, the actual type of a dynamic type variable would be resolved at run-time.
In C# 4.0, a new type is introduced that is known as a dynamic type. It is used to avoid the compile-time type checking. The compiler does not check the type of the dynamic type variable at compile time, instead of this, the compiler gets the type at the run time.
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);
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