Breaking news, C# 4.0 finally catches up to Classic VB!

This bit of nostalgic humour will be lost on n00b developers, or anyone lucky enough to have missed out on developing in VB6 (or older–I think these features were introduced in VB4 or 5, but can’t recall for sure).

C# has finally decided to embrace optional parameters and named arguments!

That’s right.  It only took 4 versions to catch up to what you were doing well before the .NET days.  Oh well, better late than never!

Of course, you could at least partially work around this in C# 3.0 and older by putting the method implementation in the most verbose signature version of your method and creating any number of overloads needed.

Using the example from the blog posting linked above (please read it before continuing), you’d create:

//main method with all the parameters and full implementation
public void SomeMethod(int a, int b, int c)
{
/* put the actual implementation here */
}

//overload to omit the c parameter and default to 100
public void SomeMethod(int a, int b)
{
SomeMethod(a, b, 100);
}

//overload to omit the b and c parameters and use the defaults 50 and 100, respectively
public void SomeMethod(int a)
{
SomeMethod(a, 50, 100);
}

However, if we then want an overload that omits the b parameter only, we run into trouble.  If we try this:

public void SomeMethod(int a, int c)
{
SomeMethod(a, 50, 100);
}

We would end up with a compile error, since the signature of this overload would be the same as the first overload I declared above, namely:

public void SomeMethod(int, int)

If a, b, and c were of different datatypes, we could declare any combination of parameters, but this example of all int’s does demonstrate the weakness of this approach, and why the new optional parameters and named arguments is so exciting!

Advertisements

0 Responses to “Breaking news, C# 4.0 finally catches up to Classic VB!”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s




Scott’s recent tweets…


%d bloggers like this: