Does C# have default parameters?

Does C# have default parameters?

Rate This
  • Comments 39

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]

Leave a Comment
  • Please add 7 and 3 and type the answer here:
  • Post
  • 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.
  • 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.
  • 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.
  • 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.
  • Screw Default Parameters, give us VB's OPTIONAL parameters so I don't have to write 6 overloads all the time....!! Please.
  • If there are issues with compiler-inserted default values when calling the method, then why not have the compiler generate the overloaded stub methods?
  • 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.
  • 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.
  • 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.
  • 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.
  • 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
  • 這是我長久的疑問,也是長久以來C#被罵到臭頭之處,因為C 、VB6、VB.NET,就連T-SQL都有default value,為什麼C#沒有呢?我翻譯了Eric Gunnerson的博客,Eric是C# team的重要成員,我想某種程度可以解釋為什麼C#到了2.0還是不願意提供default value的原因。

Page 1 of 3 (39 items) 123