You need to specify the BindingFlags
for reflection to find it:
(T)Activator.CreateInstance(typeof(T),
BindingFlags.Instance | BindingFlags.NonPublic,
null
new object[] { barProperty },
null);
Now, in this case you do need to build an object[]
because it's not a params
.
As Matthew Watson stated, I should clarify the way reflection works. And maybe more specifically modifiers. They [modifiers] aren't built for real protection. They are built to determine the API that's available when you're using the types.
Reflection however, works directly off the modifier. If it's public
- then with reflection it's public
. It doesn't matter the hierarchy. Remember, reflection can actually access private
members. I know, I've had to hack a few things like that before.
Further, constructors don't inherit the modifier of the class
. The default constructor - that's generated by the compiler if you don't define it - is always public
.