Matthias Müller
Matthias Müller

Reputation: 3473

Reflection Get the internal variable result value

In our reporting environment we have a method to get the DataSources, which is looking like this:

protected override IEnumerable<ReportDataSource> GetDataSources(IEnumerable<ReportParameter> parameters)
{
    return new List<ReportDataSource>
    {
        new ReportDataSource("DataSource1", GetDataSource1(parameters)),
        new ReportDataSource("DataSource2", GetDataSource2(parameters))
    };
}

The values from the methods called are just ICollections. My problem is, I need to know the internal Type of these collections for documentation-purposes, at best without having to invoke the method. I just need the calls they're making, I broke this down to the local variable via:

const string dataSourcesMethodName = "GetDataSources";

MethodInfo methodInfo = type.GetMethod(
    dataSourcesMethodName,
    BindingFlags.Instance | BindingFlags.NonPublic,
    Type.DefaultBinder,
    new[] { typeof(IEnumerable<ReportParameter>) },
    null);

    var methodBody = methodInfo.GetMethodBody();
    var variable = methodBody.LocalVariables.First(f => f.LocalType == typeof(IEnumerable<ReportDataSource>));

Is it even possible to get the information I need without invoking this method?

Upvotes: 0

Views: 127

Answers (1)

xanatos
xanatos

Reputation: 111870

Simply put, you can't without executing the method... some examples (see http://goo.gl/8QN19K):

C#:

public ICollection M1() {
    ICollection col = new List<string>();
    return col;
}

public ICollection M2() {
    ArrayList col = new ArrayList();
    col.Add("Hello");
    return col;
}

IL code locals:

.locals init (
    [0] class [mscorlib]System.Collections.ICollection,
    [1] class [mscorlib]System.Collections.ICollection
)

and

.locals init (
    [0] class [mscorlib]System.Collections.ArrayList,
    [1] class [mscorlib]System.Collections.ICollection
)

Compiling in Release mode it is even worse, the locals could totally disappear... See for example http://goo.gl/yvWZHR

In general those methods could use for example an ArrayList, so an untyped collection (as in the M2 method). Good luck finding the type of its elements without executing the method and parsing some elements.

Upvotes: 1

Related Questions