0
votes

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

1
public static void MyMethod() that's not non-static. and NO you cannot call a non-static method without creating an instance.Bala R
Did you mean to make MyMethod static?Sven
Just out of curiousity - what are you hoping to achieve?RB.
Why are you trying to do this?Peter Lillevold
@Bala I've removed the static keyword, my mistake :(Arslan

1 Answers

3
votes

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

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