Reflection.Emit private property access
<p>I'm using <code>Reflection.Emit</code> to generate getters for properties on the fly. So far, my code works in all cases I've tested except where the property isn't public, or is public with a private accessor. The PropertyInfo's are passed in by iterating over the results of GetProperties. When the property isn't public, calling the <code>delegate</code> throws </p>

<p><code>"System.NullReferenceException : Object reference not set to an instance of an object."</code></p>

<p>I'm using this code to generate: (<code>property</code> is a <code>PropertyInfo</code>)</p>

<pre><code>// Get setter or return null
MethodInfo setMethod = property.GetSetMethod ();
if (setMethod == null)
    return null;

// Method names follow the pattern: "_Set&lt;Property&gt;_"
DynamicMethod dm = new DynamicMethod(String.Concat ("_Set", property.Name, "_"), typeof(void),
                                     new Type[] { typeof(object), typeof(object) },
                                             property.DeclaringType, true);
ILGenerator generator = dm.GetILGenerator ();
generator.Emit (OpCodes.Ldarg_0);
generator.Emit (OpCodes.Castclass, property.DeclaringType);
generator.Emit (OpCodes.Ldarg_1);

if (property.PropertyType.IsClass)
    generator.Emit (OpCodes.Castclass, property.PropertyType);
else
    generator.Emit (OpCodes.Unbox_Any, property.PropertyType);

generator.EmitCall (OpCodes.Callvirt, setMethod, null);
generator.Emit (OpCodes.Ret);

return (Action&lt;object, object&gt;)dm.CreateDelegate (typeof(Action&lt;object, object&gt;));
</code></pre>
