views:

102

answers:

3

I have the below code that was working fine until I tried adding the bool NetworkAvailable = true portion. Now I get a Method name expected compile time exception at Line 4 below.

void NetworkStatus_AvailabilityChanged(object sender, NetworkStatusChangedArgs e)
{
   var networkAvailable = e.IsAvailable;
   SetUpdateHUDConnectedMode d = new SetUpdateHUDConnectedMode(UpdateHUDConnectedMode(networkAvailable));
   this.Invoke(d);
}   

delegate void SetUpdateHUDConnectedMode(bool NetworkAvailable = true);
private void UpdateHUDConnectedMode(bool NetworkAvailable = true)
{
   ...
}

I am, admittedly, new to Delegates and Optional Parameters so I would be grateful for any insight. Thanks.

+3  A: 

A delegate points to a method definition.
When you instantiate a delegate pointing to a method, you cannot specify any parameters.

Instead, you need to pass the parameter values to the Invoke method, like this:

SetUpdateHUDConnectedMode d = UpdateHUDConnectedMode;
this.Invoke(d, e.IsAvailable);
SLaks
Thanks, it looks like my delegate needs to have the parameter declared as well, like this -->` delegate void SetUpdateHUDConnectedMode(bool NetworkAvailable = true);`, correct? I am assuming so since it won't compile the other way but...
Refracted Paladin
Yes; the delegate _definition_ must define which parameters the delegate takes. A delegate type defines a function signature which the method(s) in the delegate must match.
SLaks
That is what I thought too. I am glad I am on the right track as `delegates` are turning out to be not, quite, as bad as I thought they would.
Refracted Paladin
Note, by the way, that you can also use the built-in generic `Action<bool>` delegate.
SLaks
I will have to read up on generic delegates as I have not used them. Thanks for the suggestion though.
Refracted Paladin
Kind of a follow up question but do I have to include a parameter with my Invoke call now? This like of code, elsewhere, now throws a runtime exception. `this.Invoke(d);`
Refracted Paladin
The WinForms `Invoke` method is not aware of optional parameters. Therefore, you need to pass every parameter to `Invoke`. The delegate itself is aware of optional parameters, so you can (but don't want to) write `d();` without parameters.
SLaks
So for WinForms does that, somewhat, defeat the point of Optional Parameters?
Refracted Paladin
A: 
SetUpdateHUDConnectedMode d = UpdateHUDConnectedMode;
vc 74
+2  A: 

To some very limited extent. Using C# 4 :

 public delegate void Test(int a, int b = 0);

 static void T1(int a, int b) { }
 static void T2(int a, int b = 0) { }
 static void T3(int a) { }


    Test t1 = T1;
    Test t2 = T2;
    Test t3 = T3;   // Error

And then you can call

    t1(1);
    t1(1, 2);
    t2(2);
    t2(2, 3);
Henk Holterman