Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why delegate must be static?

In code below I must declare method MdrResponseInterpreter static otherwise I have compilation error.

class.... {

    private StandardBuilder _mdrResponseBuilder = 
      new StandardBuilder(MdrResponseInterpreter);

    public static bool MdrResponseInterpreter(DNMessageDeliverer builder, 
                                              DNFieldSet message)
    {
        // .... work
    }

Why? As _mdrResponseBuilder is not static I expect that MdrResponseInterpreter should be able to access this

like image 272
Oleg Vazhnev Avatar asked Mar 28 '12 09:03

Oleg Vazhnev


People also ask

Are delegates static?

Static delegates are not without limitations. They can only refer to static functions; member methods on objects are not permitted because there is no place to store the pointer to the object. Furthermore, static delegates cannot be chained to other delegates.

Can we call static method from delegate?

No need to create a static method to pass in delegate. But the non static method should be declared in different class and have to be accessed with instance of that class.

Are delegates immutable?

Although the term combining delegates might give the impression that the operand delegates are modified, they are not changed at all. In fact, delegates are immutable. After a delegate object is created, it cannot be changed.

What is a delegate How is it type safe?

A delegate is a type-safe function pointer that can reference a method that has the same signature as that of the delegate. You can take advantage of delegates in C# to implement events and call-back methods. A multicast delegate is one that can point to one or more methods that have identical signatures.


1 Answers

Because field initializers don't have access to this / instance members. Move the initialization to the constructor if you want access to instance members.

The spec says:

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer

While your code doesn't explicitly reference this, the method group to delegate conversion does reference this implicitly if the method is an instance member.

like image 140
CodesInChaos Avatar answered Oct 20 '22 14:10

CodesInChaos