Reputation: 4453
If I have a function
public IEnumerable<string> GetStrings()
{
return new string[]{"all","my","strings"};
}
Is there any way I can determine the "real" type of the returned value (string[])? Reflection gives me:
Name: "IEnumerable`1"
Namespace: "System.Collections.Generic"
FullName: "System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"
The end goal is to instantiate an object of this type, serialize it and use as an example for api discovery.
Upvotes: 1
Views: 56
Reputation: 20764
It's so easy.
var result = GetStrings();
var returnType = result.GetType();
It is not possible to get the real return type without calling the method. What if the method is something like this?
Random random = new Random();
public IEnumerable<string> GetStrings()
{
var randomValue = random.Next();
if (randomValue % 5 == 3)
return new string[] { "all", "my", "strings" };
else if (randomValue > 15)
return new List<String>() { "all", "my", "strings" };
else if (randomValue > 25)
return new HashSet<String>() { "all", "my", "strings" };
return null;
}
Upvotes: 2
Reputation: 136174
Reflection will not help you here, it can only tell you what the signature of the method says it returns (In your case an IEnumerable<string>
).
One way to find out, is to call the method and examine the returned object
var result = myInstance.GetString();
Console.WriteLine(result.GetType()); // System.String[]
Upvotes: 1