Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Delegate have an optional parameter?

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.

like image 585
Refracted Paladin Avatar asked Sep 21 '10 17:09

Refracted Paladin


People also ask

Can parameters be optional?

The definition of a method, constructor, indexer, or delegate can specify its parameters are required or optional. Any call must provide arguments for all required parameters, but can omit arguments for optional parameters. Each optional parameter has a default value as part of its definition.

Can we pass delegate as parameter?

You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

Can we have optional out parameter C#?

Func(out i); then the answer is no you cant. also C# and . NET framework hast many many data structures that are very flexible like List and Array and you can use them as an output parameter or as return type so there is no need to implement a way to have optional output parameters.

How do you pass an optional parameter?

By Params Keyword: You can implement optional parameters by using the params keyword. It allows you to pass any variable number of parameters to a method. But you can use the params keyword for only one parameter and that parameter is the last parameter of the method.


2 Answers

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);
like image 132
Henk Holterman Avatar answered Oct 09 '22 16:10

Henk Holterman


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);
like image 45
SLaks Avatar answered Oct 09 '22 15:10

SLaks