Why doesn't C# support default parameters?

Published 07 March 04 12:40 PM

Update:

Named and optional (default) parameters are available starting from C# 4.0. For more information, see Named and Optional Arguments (C# Programming Guide).

 

In languages such as C++, a default value can be included as part of the method declaration:

void Process(Employee employee, bool bonus = false)

This method can be called either with:

a.Process(employee, true);

or

a.Process(employee);

in the second case, the parameter bonus is set to false.

C# doesn't have this feature.

One reason we don't have this feature is related to a specific implementation of the feature. In the C++ world, when the user writes:

a.Process(employee);

the compiler generates

a.process(employee, false);

In other words, the compiler takes the default value that is specified in the method prototype and puts it into the method call - it's just as if the user wrote 'false' as the second parameter. There's no way to change that default value without forcing the user of the class to recompile, which is unfortunate.

The overloading model works better in this respect. The framework author just defines two separate methods, and the single-parameter one calls the two-parameter method. This keeps the default value in the framework, where it can be modified if necessary.

It would be possible for a compiler to take something like the C++ definition and produce the overloads, but there are a few issues with that approach.

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

Writing overloads yourself is a bit less convenient, but we think it's an acceptable solution.

[Author: Eric Gunnerson]

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

# Eric Gunnerson's C# Compendium said on March 7, 2004 3:42 PM:
# Roy J. Salisbury said on March 7, 2004 4:18 PM:
# Christian Nagel's OneNotes said on March 7, 2004 4:23 PM:
# Robert Jacobson said on March 7, 2004 6:05 PM:
I understand why it makes sense for C# not to allow you to *define* a function with default parameters. However, these justifications don't really hold up for *calling* a function that's defined in a different language.

For example, the Microsoft Office COM automation model is filled with default parameters. (Some functions have as many as 30 default parameters -- maybe it's a bad interface design, but we're stuck with it for the time being.) Because C# doesn't support these default parameters, we have to fill in "Type.Missing" for each parameter, which reduces readability/maintainability. To be blunt, this is a real PITA -- it makes C# less suitable than VB.Net for serious Office automation interop.

It would be nice if C# could take a middle ground here -- not allow you to define functions with default parameters, but allow you to call functions in other languages using default parameters.
# Damien McGivern said on March 7, 2004 7:04 PM:
I totally disagree with Robert. When I am reading code for the first time that uses default parameters it assumes that I know about the default parameters of all the methods of the server code as of course they don't appear in the client code. I believe the opposite is true that default parameters reduced the readability/maintainability of the code for as it requires you to constantly check that if default parameters are used for each method. "maybe it's a bad interface design" - yep your right default parameters are. I see C# as an evolution in computing languages and I think the designers were right to kill off this feature. Also what if the server code changes the default parameters vaules in a future version? Then your really screwed.
# Chango V. said on March 7, 2004 8:46 PM:
I fully agree with Robert. C# is a real pain to work with COM interfaces. It may sound ridiculous, but we are finding it more practical to use VB.NET to call COM-based APIs.

Coming from C++, I'm personally sickened to see the long lists of overloaded methods in the .NET Class Library. See, often it's just not that optional parameters hide values that get passed by the compiler anyway. Rather, it may be that these parameters are irrelevant, given specific values for the other required parameter(s), or the default values can actually mean 'no specific/explicit value provided here'. Random examples:
Debug.Assert(bool, string msg = null);
[XmlElementAttribute(string elemName, Type type = null)];
File.Open(string fn, FileMode, FileAccess fa = FileAccess.ReadWrite);
XmlSerializer.Serialize(Stream, object, XmlSerializerNamespaces = null).
When used reasonably, optional parameters can really prevent unnecessary bloat and redundancy in APIs. And IntelliSense can actually be much more helpful because it will know more often than now which particular overload you are trying to use.
# John Cass said on March 8, 2004 12:42 PM:
My first thoughts when I tried to define a default parameter and found I couldn't were surprise and disbelief. But reading the debate so far I think I can accept that overloads are better. One thing I always felt uneasy about in C++ was that you could not easily tell from a function definition whether or not a parameter had a default value, so you had to resort to inline comments as reminders.
Office calls are something else, with crazy parameter lists, 90% of which are never used in practice. Perhaps if optional parameters had not been allowed in COM interfaces we would have had altogether better interface definitions :-). I am getting round the problem by writing class wrapper functions for the actual calls which only pass the parameters that are normally needed. Properties can be then be used to change the default values in the actual calls if necessary.
# Just a Developer said on March 8, 2004 5:40 PM:
Screw Default Parameters, give us VB's OPTIONAL parameters so I don't have to write 6 overloads all the time....!! Please.
# Vulcannis said on March 9, 2004 10:19 AM:
If there are issues with compiler-inserted default values when calling the method, then why not have the compiler generate the overloaded stub methods?
# Michael Duncan said on March 9, 2004 6:42 PM:
Well I think it's a bit mysterious when one (VB.NET) of the first two OO .NET languages supports default arguments and the other (c#) doesn't.
# Chris Nahr said on March 10, 2004 12:24 AM:
How about just allowing the default initializer values for default parameters? That is, null, zero, false. That should be appropriate for most cases, and it takes care of default parameters that do crazy things when you omit them, or whose default value might change in future builds.
# Daniel O'Connell said on March 10, 2004 12:30 AM:
Vulcannis:
Because it won't work, atleast not in any simple way.
Consider a method with(pseudo-syntax)

public Method(optional string var1, optional string var2, optional string var3);

To achieve all possible combinations with overloading, you need:
public Method(string var1)
public Method(string var2)
public Method(string var3)
public Method(string var1,string var2)
public Method(string var1,string var3)
public Method(string var2,string var3)
public Method(string var1, string var2, string var3)

That gives you conflicting overload definitions, effectivly limiting you to only 3 possibliitys(string var1), (string var1, string var2), and (string var1, string var2, string var3). This not only doesn't effectivly expose the nuances of a method with optional parameters, it is also *very* confusing.

You could define stub methods and use some compiler tricks and some small syntax additions(named parameters(var1="x") and empty parameters(var1Val,,var3Val)) but that results in far worse outcomes than just using the constants as optional parameters currently do. You end up with the same syntax and a plethora of specialname methods for the language to deal with.

I for one don't care for optional parameters, prefering overloads, but I would like to see support in the IDE for displaying the default value when provided(I don't believe it currently does so, although I could be wrong).
Also note, if you currently wish to you can mark a value as optional via the System.Runtime.InteropServices.OptionalAttribute(can't remember how to set the default value, I think its another attribute), C# still won't consume it.

Michael:
The question is more would VB have included it if optional parametesr hadn't existed in vb6? However, they were in vb6 and were a legacy that they probably couldn't even consider removing. That isn't to say the VB team would have dropped optional parameters, I don't know, but more to say that they probably couldn't even consider if it was a good idea or not, they were stuck with optional parameters by legacy.
# Tom Jordan said on June 9, 2004 2:10 AM:
Hogwash.
Eliminating the ability for the framework writer.
You are making it tedious for us to write them.
If a programmer is too lazy to look up in the
docs what the parameters are, he doesn't
understand how the purpose, requirements and
side-effects of the method.
But your arguement states that it would be
too difficult for the /doc portion of the
compiler to handle default parameters.
Who cares .... just pick out the defaults
from the method signature and add them to
the generated docs. I mean you have
reflection by goodness. Iterate through the
similiar method names.

Don't sacrifice the convience of default
method parameters for the inability or
lack of intestinal fortitude to tackle
the /doc feature robustly.
# Sachin Bhatt said on July 26, 2004 1:02 AM:
Overloaded Functions don't serve the purpose all the times.
Assuming i want something like
function A(string a)
{
dosomething
}

[fictional function declaration]
function A(string a,bool b=false)
{
dosomething
if(b)
dox
else
doy
}

I can't have overloaded function in this scenario
function A(string a) {}

function A(string a)
{ assume default false }

function A(string a,bool b)

Ofcourse some would argue that I can give different function name for the last 2 declarations but this approach is not very user friendly
# 真 OO无双 said on June 28, 2007 12:10 PM:

這是我長久的疑問,也是長久以來C#被罵到臭頭之處,因為C 、VB6、VB.NET,就連T-SQL都有default value,為什麼C#沒有呢?我翻譯了Eric Gunnerson的博客,Eric是C# team的重要成員,我想某種程度可以解釋為什麼C#到了2.0還是不願意提供default value的原因。

# journal.stuffwithstuff.com » Blog Archive » Avoiding Overload Hell in C# said on February 26, 2008 9:35 AM:

PingBack from http://journal.stuffwithstuff.com/2008/02/26/avoiding-overload-hell-in-c/

# Will’s Blog - Pains of Moving from VB.NET to C# - Optional Method Parameters said on August 18, 2008 10:27 PM:

PingBack from http://will.hughesfamily.net.au/20080819/pains-of-moving-from-vbnet-to-c-optional-method-parameters/

# Serge’s Technology View » Blog Archive » Delphi, methods and default values. Convenience or contract enforcement? said on August 28, 2008 10:28 AM:

PingBack from http://blog.dragonsoft.us/2008/08/28/delphi-methods-and-default-values-convenience-or-contract-enforcement/

# Sobre C#, LINQ y algo más... said on October 30, 2008 5:49 PM:

Comentaba mi buen amigo Luis en respuesta a un post anterior que, a pesar de todo, no le gusta la idea

# Sobre C#, LINQ y algo más... said on October 30, 2008 8:02 PM:

Comentaba mi buen amigo Luis en respuesta a un post anterior que, a pesar de todo, no le gusta la idea

# LA.NET [EN] said on November 10, 2008 4:21 PM:

After several failed tries, I finally managed to configure my home PC so that it runs the Server 2008

# ASPInsiders said on November 10, 2008 5:13 PM:

After several failed tries, I finally managed to configure my home PC so that it runs the Server 2008

# Default Parameters - CodeCall Programming Forum said on November 21, 2008 7:48 AM:

PingBack from http://forum.codecall.net/c-programming/12017-default-parameters.html#post100093

# A revelation :) « Tech That… said on January 11, 2009 9:36 PM:

PingBack from http://sankalpshere.wordpress.com/2009/01/11/a-revelation/

# gibt es in C# optionale Parameter? - Seite 2 | hilpers said on January 20, 2009 9:53 AM:

PingBack from http://www.hilpers.com/274108-gibt-es-in-c-optionale/2

# Asignacion de valores a parametros de metodos. | hilpers said on January 20, 2009 2:42 PM:

PingBack from http://www.hilpers-esp.com/446038-asignacion-de-valores-a-parametros

# C Frequently Asked Questions Why doesn t C support default parameters | basketball hoop said on June 18, 2009 2:36 AM:

PingBack from http://thebasketballhoop.info/story.php?id=2690

# Giorgio Malagutti said on November 2, 2009 6:28 AM:

I need the ability to expose optional parameters to COM calls to guarantee full backward compatibility with legacy code, but if I can obtain the same that in any other way, including annotations I wouldn't mind doing so.

# DeveloperChris said on November 15, 2009 2:10 PM:

This is my first foray into c#. So this baffles me. Why would I want to write 2 functions (overloads) to achieve the same thing I can do in one. Default parameters are a convenience thing. removing them is suitably Microsoft thing to do - daft -

To say its harder for document generation is a cop-out. We write compilers to reduce the workload for programmers not to increase it.

Most of the time the default parameter is used for that 1 in 30 type of call when something a less common is required. To force the programmer to enter all parameters all the time is again time wasting. Damien McGivern if you have to check the default parameter all the time you ain't doing it right.

In fact without default parameters you have to check the docs more often wondering what the F that parameter is for.

DC

# Alexandra Rusina said on November 18, 2009 11:32 AM:

Named and optional (default) parameters are available starting from C# 4.0. For more information, see http://msdn.microsoft.com/en-us/library/dd264739(VS.100).aspx

Leave a Comment

(required) 
(optional)
(required) 

  
Enter Code Here: Required

This Blog

Syndication

Page view tracker