0

I have defined a delegate field inside a class and I am initializing that delegate field directly inside a static function (without making an object). It should not work, because there is no object of the class and the delegate field is not static. But it works. Can anyone please explain how it works. I have copied some of my code below for reference:

class Test
{

  delegate void CustomDel(String s);

  static void main()
  {
   CustomDel del1, del2, del3; //it shouldn't work, but is working.
  }
}

1 Answer 1

2

This doesn't do what you think:

delegate void CustomDel(String s);

It's not a field, it's a delegate type definition. Think of it as something like:

private class CustomDel : Delegate
{
    // ...
}

The code above won't compile because you can't declare delegates like that, but it's essentially what happens under the hood:CustomDel is a type, only a special one.

Now your code should make more sense:

CustomDel del1, del2, del3;

This only declares three local variables of the CustomDel type.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.