Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why an identifier is expected while declaring a delegate?

Tags:

c#

When we create a delegate in C#, to point a function with a definite signature (parameter set), it asks us to specify the identifier also for each type.

public delegate void myDelegate(int x, int y);  

if I try to write this prototype declaration as:

public delegate void myDelegate(int, int)

it shows a compile time error saying identifier expected.

But according to me, when we are just specifying the prototype for the method, why compiler needs an identifier to distinguish between two methods with different signature:

public delegate void firstDelegate(int);

and

public delegate void secondDelegate(int, int);

are the sufficient and clear declaration to distinguish between them. I think so

I think you people got me??

like image 678
Manish Dubey Avatar asked Feb 14 '23 07:02

Manish Dubey


1 Answers

It can make a difference at the point of invocation. For example:

using System;

class Test
{
    delegate void Foo(int x, int y);

    static void Main()
    {
        Foo foo = (x, y) => Console.WriteLine("x={0}, y={1}", x, y);
        foo(x: 5, y: 10);
        foo(y: 10, x: 5);
    }
}

The output is x=5, y=10 for both lines, because the arguments use names rather than positions. Even though C# only gained named arguments in C# 4, VB.NET has had them for much longer.

Now of course it didn't have to be like that. It could have been designed so that delegates didn't have named parameters in the first place - but when everything else you invoke has named parameters, why would you want to make delegates different?

Would you propose the same for interface methods and abstract methods, by the way? Again, there's no direct use of the parameters in the declarations, as they're just signatures.

Note that parameter names help in terms of readability and allow the parameters to be documented more easily too.

like image 175
Jon Skeet Avatar answered Feb 16 '23 03:02

Jon Skeet