Optional Parameters and Delegates
Posted
Mon, Apr 12 2010 22:27
by
Deborah Kurata
This prior post mentioned that optional parameters can be used in delegates. While this is true for C#, it is not true in VB.
The prior post covered the new optional parameters feature in C# 4.0. It also included the comparable VB.NET code since VB has had optional parameters from the beginning. This post provides an example of using an optional parameter in a delegate.
In this case, the PerformCalculation delegate can perform a calculation using two or three values with the third value being optional.
In C#:
public delegate int PerformCalculation(int x, int y, int z = 0);
public int Add(int x, int y, int z = 0)
{
return x + y + z;
}
private void Form1_Load(object sender, EventArgs e)
{
PerformCalculation pc = Add;
int x = pc(4, 5);
}
The first line declares the PerformCalculation delegate. Defining the last parameter with a default value indicates that it is an optional parameter.
The Add method also has an optional parameter. It adds the three values, setting the last parameter to 0 if it is not defined.
Then, the load method creates an instance of the delegate using the short-hand syntax and assigns it to the Add method.
Finally, the delegate instance is called passing either two or three arguments.
In VB:
Attempting to use an optional parameter in a delegate in VB generates a compile error:
So optional parameters in delegates is only available in C#.
Enjoy!