1

So, here's the deal. I have an interface called IBehavior. Each one of my Entity's has a variable: private IBehavior _behavior. Each Entity also has a variable: public string Behavior. Upon loading my entitys the string is filled from an xml file. Subsequently a function called init() is called on all entitys. This method takes the string and uses this line of code to call the desired constructor: Type.GetType(Behavior).GetConstructor(Type.EmptyTypes).Invoke(null);.

Unfortunately, the Invoke() method returns something of type Object, and the _behavior variable wont accept this without a cast. I have tried this approach: _behavior = (IBehavior)Type.GetType(Behavior).GetConstructor(Type.EmptyTypes).Invoke(null);.

All this did was tell me that my _bahavior variable was null and therefore this could not happen. I'm probably using GetConstructor() incorrectly. Can someone please point me in the right direction?

Init Function:

public void Init()
{
  if (Behavior == "null" || Behavior == "none")
  {
    _behavior = null;
    return;
  }

  _behavior = (IBehavior) Type.GetType(Behavior).GetConstructor(Type.EmptyTypes).Invoke(new object(), null);
}
1
  • If more information is needed let me know what you'd like to see and I'll add it in an edit. Also I apologize if this is a repost but I haven't found anything that has solved my problem yet. Commented Jan 11, 2014 at 0:42

1 Answer 1

3

To create type from its name use:

_behavior = (IBehavior)Activator.CreateInstance(Type.GetType(Behavior));

The other problem with your code is that you are calling constructor on new object() because you use MethodBase.Invoke(Object, Object[]) method:

.GetConstructor(Type.EmptyTypes).Invoke(new object(), null)

and by specifying only array of object, you use ConstructorInfo.Invoke(Object[]) method:

_behavior = (IBehavior)Type.GetType(Behavior)
                           .GetConstructor(Type.EmptyTypes)
                           .Invoke(new object[] { });

Note: If you receive ArgumentNullException from Activator.CreateInstance, remember that type must be specified with namespace (if defined in the same assembly), like:

Activator.CreateInstance(Type.GetType("ConsoleApplication.SomeClass"))
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you. Any Idea why this would cause an ArgumentNullException?
@user1311199, maybe constructor of created type has a parameter and you are passing null to it with Invoke(new object(), null)?
I'm sorry i should have phrased that better, but I replaced Invoke(new object(), null) with Activator.CreateInstance(Type.GetType(Behavior)); and CreateInstance() is throwing the ArgumentNullException.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.