Pranav Raj
Pranav Raj

Reputation: 873

using delegate inside a static function

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.
  }
}

Upvotes: 0

Views: 215

Answers (1)

Lucas Trzesniewski
Lucas Trzesniewski

Reputation: 51330

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.

Upvotes: 2

Related Questions