A revelation: C# doesn’t allow default parameters

11 01 2009

Wondering why?

Check out: http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx.

Quoting their reasons below:

1. The first one is that the correlation between the code that the user writes and the code the compiler generates is less obvious. We generally try to limit magic when possible, as it makes it harder for programmers.

2. The second issue has to do with things like XML doc comments and intellisense. The compiler would have to have special rules for how it generates doc comments for the overloaded methods, and intellisense would need to have smarts to collapse the overloaded methods into a single method.

The first reason kind of makes sense. Allowing default parameters is like forcing the programmer to know about default parameters before using them. Although, default parameters can make your program look magical(!) (initializing something without doing anything), it makes it harder to read.

It sucks if you are used to default parameters.

Check out this link for more How To’s or FAQs in C#.

Sources:

1. http://blogs.msdn.com/csharpfaq/archive/2004/03/07/85556.aspx

2. http://blogs.msdn.com/csharpfaq/default.aspx

Advertisements

Actions

Information

3 responses

11 01 2009
eksith

Yes, but you can simulate default parameters by using the same function name with different parameters

`
// The “default” simulator
private string myfunction()
{
return myfunction(false, false);
}

// Actual function
private string myfunction(bool opt1, bool opt2)
{
// Actual code here…
return something;
}
`

It’s a pain at first, but once your functions are created, you don’t have to worry about it afterwards.

12 01 2009
sankalpshere

that is right, and i am aware of this workaround.
but i always thought that one of the main uses of default parameters is not having to write polymorphic constructors/functions…

i.e. in above mentioned functions, if opt1 & opt2 were optional parameters, for all of the following calls I could write only one function:

myfunction(true);
myfunction(true,false);
myfunction();

12 01 2009
eksith

Yeah that would shave a time off a project and keep your code a lot cleaner.
There were rumours floating around that the upcoming C# 4.0 would have this feature, but I doubt it.

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




%d bloggers like this: