Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dynamic return type of a function

Tags:

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 ;   } 
like image 565
DevMania Avatar asked Apr 13 '09 16:04

DevMania


People also ask

Can dynamic be used as return type in c#?

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.

What does dynamic data type mean?

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.

What are dynamic type variables?

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.

What is dynamic type C#?

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.


1 Answers

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); 
like image 75
Adam Robinson Avatar answered Sep 21 '22 04:09

Adam Robinson