Jason Hu
Jason Hu

Reputation: 6333

Can C# return a type in a method?

can i have something like:

AMess.Foo = MessyData.GetData<MessyData.GetType(key)>(key);

?

my problem is similar to my example. I have a data source is dynamically typed, so i have to do something to determine the data type. but it's a pain in the ass to put type check everywhere. so i think maybe i could have some code just to tell me what type it is. can i do this?

or maybe better solution?

please not worry about AMess.Foo, it eats everything.

Upvotes: 0

Views: 92

Answers (2)

Jeppe Stig Nielsen
Jeppe Stig Nielsen

Reputation: 61912

No. Generic type arguments must be resolved at compile-time.

If you use:

MessyData.GetData<SomeType>(key);

then SomeType needs to be the name of a specific class (or interface, struct, etc.). It can never be an expression like in your question.

If you let the type be inferred, as in:

MessyData.GetData(key); // infer type arg

then the type used in the call is the compile-time type of the key variable, not the run-time type. These types can differ.

If you really want dynamic typing, you can have GetData take in a parameter of type dynamic (the method will be non-generic). But what is the problem you are trying to solve?

Upvotes: 1

Justin Niessner
Justin Niessner

Reputation: 245389

No, it can't. You'll have to use Reflection instead. I don't have Visual Studio installed on my machine at the moment so I can't test the syntax at the moment, but this should be close:

var type = MessyData.GetType(key);
var castMethod = MessyData.GetType().GetMethod("GetData").MakeGenericMethod(type);
AMess.Foo = castMethod.Invoke(MessyData, new[] { key });

Upvotes: 2

Related Questions