Arslan
Arslan

Reputation: 569

C# calling a public non-static method using reflection without instantiating its class

Is-it possible in C# to call a method (non-static) without instantiating its class e.g :

public class MyClass
{
    public void MyMethod()
    {
        Console.WriteLine("method called");
    }
}

I've tried this method using the System.Reflection.Emit namespace, I copied the IL of MyMethod() to a dynamic method but got an exception :

FatalExecutionEngineError was detected : The runtime has encountered a fatal error. The address of the error was at 0x5dceccf5, on thread 0x2650. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

        Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
        Type t = a.GetType("Tutorial.MyClass");
        MethodInfo m = t.GetMethod("MyMethod");
        MethodBody mb = m.GetMethodBody();

        DynamicMethod dm = new DynamicMethod("MethodAlias", null, Type.EmptyTypes, typeof(Tutorial.MainWindow), true);
        DynamicILInfo ilInfo = dm.GetDynamicILInfo();
        SignatureHelper sig = SignatureHelper.GetLocalVarSigHelper();
        ilInfo.SetLocalSignature(sig.GetSignature());
        ilInfo.SetCode(mb.GetILAsByteArray(), mb.MaxStackSize);

        try
        {
            dm.Invoke(this, null);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }

Thank you

Upvotes: 0

Views: 1462

Answers (1)

Jeff Sheldon
Jeff Sheldon

Reputation: 2094

Not that I know of. Because it's not static.

I would just say "No" but my reply wasn't long enough for SO.

Upvotes: 3

Related Questions