Deborah's Developer MindScape

         Tips and Techniques for Web and .NET developers.

April 13, 2010

Optional Parameters and Delegates

Filed under: C#,VB.NET @ 12:27 am

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#.



  1.   Rostov — April 16, 2010 @ 8:53 am    Reply

    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.

  2.   Isak — March 9, 2011 @ 3:28 pm    Reply

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

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2020 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs