Eugene
Eugene

Reputation: 57

c# just-return delegate like this {return;}

How to create and use delegate like this:

    public delegate void MyDel();
    static void Main(string[] args)
    {
        MyDel myDel = delegate { return; };
        Test(myDel);
    }

    static void Test(MyDel myDel)
    {
        Console.WriteLine("111");
        myDel?.Invoke();
        Console.WriteLine("222");
    }

Output is 111 222

but I'd like to get 111.

Is it possible? Thanks!

Upvotes: 1

Views: 208

Answers (2)

Rivo R.
Rivo R.

Reputation: 351

I don't know what you really trying to do here. But in your case, with the current implementation, it is impossible to have 111 only as output. Those three statements will be executed no matter what the delegate does.

Console.WriteLine("111");
myDel?.Invoke();
Console.WriteLine("222");

However if you put the third line that outputs 222 in the delegate body surrounded with some if() { ... } statements, maybe it will print 111 only (when the conditions are not satisfied obviously).

Upvotes: 0

ng256
ng256

Reputation: 87

This is very exotic challenge. Unfortunately, I can not give you a complete answer, but I can give the direction of the search. And following article will useful to learn: .NET CLR Injection.
It might turn out like this:

class Program
{
    public delegate void MyDel();
    static void Main()
    {
        MyDel myDel = delegate
        {
            // Get the method that called this delegate.
            StackTrace trace = new StackTrace();
            var method = trace.GetFrame(0).GetMethod();

            // Get opcodes of given method.
            RuntimeHelpers.PrepareMethod(method.MethodHandle);
            byte[] ilCodes = method.GetMethodBody().GetILAsByteArray();

            for (int i = 0; i < ilCodes.Length; i++)
            {
                // Find and replace opcodes to insert a return statement.
                // ...
            }

            // Then inject opcodes back to the original method.
            // ...
        };
        Test(myDel);
    }

    static void Test(MyDel myDel)
    {
        Console.WriteLine("111");
        myDel?.Invoke();
        Console.WriteLine("222");
    }
}

This is just a guess, not 100% sure it will work. And I know, it's madskills for this task.

Upvotes: 1

Related Questions