1
namespace MyNameSpace
{
    public interface IMyInterface
    {
        string GetMethod();
    }
    public class MyClass : IMyInterface
    {
       public string GetMethod()
       {}
    }
}

//Main Program

var ruleClass = Activator.CreateInstance(Assembly.GetExecutingAssembly().FullName, "MyNameSpace.MyClass"); 
if( ruleClass != null)
{
   IMyInterface myClass = (IMyInterface)ruleClass;
   //throws exception. 
}

How can I convert ruleClass to IMyInterface type so that I can call specific methods in it?

3
  • 2
    I don't get a null value of myClass at all - I get an exception when you try to cast... Commented Aug 3, 2015 at 6:17
  • Yes. It throws an exception. UnWrap method did worked for me. Commented Aug 3, 2015 at 6:27
  • Right - please be more careful when describing what you've observed in future questions. Commented Aug 3, 2015 at 6:30

3 Answers 3

5

Use Unwrap method.

IMyInterface myClass = (IMyInterface)ruleClass.Unwrap();

You can create it directly too

var myClass = Activator.CreateInstance(typeof(MyClass)) as MyClass;
Sign up to request clarification or add additional context in comments.

1 Comment

This is the right way to fix it. CreateInstance in this case returns a ObjectHandle, not a MyClass
0

Have you tried this?

var ruleClass = Activator.CreateInstance(typeof(MyClass));
if (ruleClass != null)
{
    var myClass = (IMyInterface)ruleClass;
    myClass.GetMethod();
}

Comments

0

You can try this option as well

var typ = Type.GetType("MyNameSpace.MyClass", true);
var ruleClass = Activator.CreateInstance(typ);
        if (ruleClass != null)
        {
            IMyInterface myClass = (IMyInterface)ruleClass;
            //myClass is NULL. 
        }`

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.