Reflection – Create an instance of a class through a protected method

16Sep10

I had a bit of trouble getting to this, so for self reference more than anything, I thought I d post about it.

Given the following class

	
    public class MyClass	
   {		
           private string _name;

           public string Name { get { return this._name;}}

           protected MyClass(string name)
          {
               _name = name;		
          }
  }

I thought that the following would be the way to create an instance of it:

Activator.CreateInstance(typeof(MyClass), BindingFlags.NonPublic, null, new object[] { "MyName" }, CultureInfo.CurrentCulture);

However it throws a MissingMethodException: Constructor on type ‘ReflectionCreateInstance.MyClass’ not found. However if we add the Binding Flag for instance then it works.

	
[Fact]
public void When_creating_with_activator_Must_use_apropriate_binding_flags()
{
	string myname = "MyName";

	var myClass = (MyClass)Activator.CreateInstance(
					typeof(MyClass), 
					BindingFlags.Instance| BindingFlags.NonPublic, 
					null, 
					new object[] { myname }, 
					CultureInfo.CurrentCulture);

	Assert.Equal(myname, myClass.Name);
}	
If you try this with type.GetConstructor or type.GetConstructors the result is the same. 
Checking the documentation for BindingFlag.Instance I find 
Capture
So it was a case of RTFM I guess :D
Advertisements


No Responses Yet to “Reflection – Create an instance of a class through a protected method”

  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: