BenVlodgi BenVlodgi -3 years ago 115
C# Question

Dynamically create or set the return type of a function in the function

I am attempting to create a function where the return type is determined at run-time. I know I could just return an

, however my aim is to have the typed
returned, and be recognized by the compiler and InteliSense.

I know I could cast my
after it has been returned and that would be the easiest thing to do to implement this, but that is just not the programming spirit.

Here is an example of what I'm trying to create

Note: I do not actually want Buttons and Grids... that is just for this example.

Type T;
public T Question(bool aBool)
if (aBool)
T = typeof(Button);
return new Button();
T = typeof(Grid);
return new Grid();

Now, this obviously doesn't work and I understand why. But I want to know if anyone has a way that does work, or if this is not possible with the current state of C#.

Edit: A response to comments... I understand this would seem like "magic", and I do understand that the compiler will have to figure out what my result is for this to work. The compiler/Intellisense/Visual Studio already does this for many other things. While these things are can simple like detecting unreachable code, or drawing visual previews. I am curious if this is an implemented feature.

Answer Source

The only possible way for the consumer of such a method to actually rely on the fact that the return type is dynamic is if, at least for that one method call, the return type is statically known at compile time.

There is a specific feature for a method that has some type unknown at the time the method is written, but fixed when a particular call to that method is make. That feature is called "generics".

public T Foo<T>()
    where T : new()
   return new T();

That's really the only available option for a truly dynamic return type that has much potential for really being useful.

If that's not what you want, or that is not a workable option for you, then odds are pretty high your method shouldn't have a dynamically changing return type. Instead it should have a fixed return type of some more generalized type that can have multiple implementations. Generally this would mean an interface, to which you can return one of any number of possible implementations. This should be done if the caller doesn't need to really know or care what the implementation is, but rather all they need to know is that they are given some implementation of an interface that exposes all of what they need. In your case, perhaps something like Control would be workable, if the caller only need to know that they are given some type of control, and to which the API of Control provides everything that they need to do with it.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download