About Contact me Presentations rss feed  rss

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

16 Sep 2010

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.
    public void When_creating_with_activator_Must_use_apropriate_binding_flags()
    	string myname = "MyName";
    	var myClass = (MyClass)Activator.CreateInstance(
    					BindingFlags.Instance| BindingFlags.NonPublic, 
    					new object[] { myname }, 
    	Assert.Equal(myname, myClass.Name);
If you try this with <b>type.GetConstructor</b> or <b>type.GetConstructors </b>the result is the same. 

Checking the <a href="" target="_blank">documentation for BindingFlag</a>.Instance I find </span>

<a href=""><img src="" style="display:inline;border-width:0;" title="Capture" height="370" width="674" alt="Capture" border="0"></img></a>

So it was a case of RTFM I guess :D
If you want to discuss this post, the best place right now for me is mastodon, please message me with your comment/question.