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:

image

So optional parameters in delegates is only available in C#.

Enjoy!

Filed under: , , ,

Comments

# re: Optional Parameters and Delegates

Friday, April 16, 2010 8:53 AM by Rostov

This is one of those things that I am excited for and worried about.

It's exciting because for simple methods where you want to be able to leave off, say, a boolean flag for something simple -- it consolidates code.

But where I'm way, is just from over/misuse: much like the 'trend' I've seen in some online videos of people using "var" for every member declaration.   Personally i think it makes the code messy and is not using it the way it was intended to.

But that's just my humble opinion.

Can't wait to get into some .NET 4 -- or at the very least Visual Studio 2010's IDE.

# re: Optional Parameters and Delegates

Wednesday, March 09, 2011 3:28 PM by Isak

Ok. But you can't use optional parameters in anonymous delegates though :(.

Leave a Comment

(required) 
(required) 
(optional)
(required) 
If you can't read this number refresh your screen
Enter the numbers above: