Julio Rodrigues
Julio Rodrigues

Reputation: 3413

Why it is not possible to assign a delegate to a method group?

Having the following class:

class C {
    public void OneMethod(string s) { 
    }

    public void ChangeMethods() {
        OneMethod = delegate(string s) { };
    }
}

The compiler says:

Error 1 Cannot assign to 'OneMethod' because it is a 'method group'

Why is that? Should I create a method group instead?

Upvotes: 2

Views: 1938

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1503449

You simply can't change how a class behaves like this.

Method groups are only used in method invocation expressions and when creating delegate instances.

If you want a class which can behave dynamically like this, you should perhaps look at ExpandoObject. Or if you want to be able to make your OneMethod class do something based on a delegate which varies, you can easily hook that up simply enough using a field of the relevant delegate type:

class C {
    private Action<string> action = delegate {};

    public void OneMethod(string s) { 
        action(s);
    }

    public void ChangeMethods() {
        action = delegate(string s) { };
    }
}

It's somewhat unusual to want to do this, admittedly.

Upvotes: 8

Related Questions