2

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?

Julio Rodrigues
  • 3,373
  • 3
  • 24
  • 33

1 Answers1

8

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • This idea is what I usually do. I think I got this idiom from javascript. – Julio Rodrigues Feb 23 '13 at 18:16
  • 1
    @Vandell: Then stick with it. .NET simply doesn't support changing method implementations directly like you were apparently trying. JavaScript is a completely different model. – Jon Skeet Feb 23 '13 at 18:17
  • This is fine. If you want to also "combine" delegates, that is `action += delegate(string s) { ExtraWork(s); };` with `+=` instead of `=`, maybe you shouldn't use `Action` because delegate combination doesn't work with contravariant generic delegates. But I must admit, there is absolutely nothing in the question that would indicate that combining (`+`) delegate instances is relevant (or that the contravariance is going to be important). – Jeppe Stig Nielsen Feb 23 '13 at 18:27