I understand from the api documentation that ReflectionOnlyGetType returns a type, much like GetType. The difference is that with ReflectionOnlyGetType, the type is loaded for reflection only, not for execution.
So why does this work:
Type t = Type.ReflectionOnlyGetType("System.Collections.Generic.List`1[[System.String, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", false, false);
ConstructorInfo[] cis = t.GetConstructors();
foreach (ConstructorInfo ci in cis)
{
if (ci.GetParameters().Length == 0)
{
// ! no arg constructor found! let's call it!
Object o = ci.Invoke(new Object[]{});
Console.WriteLine("But wait, it was supposed to be reflection only??");
Console.WriteLine(o.GetType().Name);
List<String> lli = (List<String>)o;
lli.Add("but how can this be?");
Console.WriteLine(lli.Count);
Console.WriteLine("I am doing a lot more than reflection here!");
}
}
My question is: I seem to be able to do more than reflect on the members of this type. Have I misunderstood “execution” when they say the type is loaded “for reflection only, not for execution”? Or is ReflectionOnlyGetType returning a different (non-reflection-only) type if the type was already “loaded” and here was loaded by virtue of being in mscorlib? Or is it something different entirely?
You are loading a type from
mscorlibwhich has already been loaded for execution by the runtime. You can check theReflectionOnlyproperty on an Assembly to see if it is loaded into a ReflectionOnly context. In your sample,It seems reflecting over mscorlib is somewhat restricted. From MSDN:
I’m guessing that extends to loading the one in the current execution context into the reflection-only context.
It seems to work with other BCL assemblies: