Some thoughts about default parameters for C#

<Sorry for posting again. I posted in .Net Framework General and then found here is a more suitable section.>
I've been troubled by this problem since I started to use C#. I always try to write classes that are easy to use. When I try to write some methods that takes several parameters, I found it was really troublesome to write different overloads. I had to give up some overloads, because there are just too many combinations, when the parameter list is long.
And I thought, why not default parameters
Anders Hejlsberg explained in an interfiew that they didn't include default parameter because they think it was not necessary. They think it's just feature that make programmer a bit easier, but not some feature that make the language more powerful.
Well I say if you can make us easier with very little effort, why not

Here is my thought.

Answer this question

Some thoughts about default parameters for C#

  • micromysore

    Your recommendation would require a constant to represent no value, as null could be interpreted as a data value that would override any default.

    I think the idea on the surface appears useful, however having default values in the method but calling it with a placeholder is much less useful than defining constants/enums and calling the method.  By using enums you can look at the calling code with much greater clarity, and make subsequent code reviews/changes much easier than having to trace down into the methods each time to figure out what the default values actually are.

    E.g.

    public void CallingMethod() {

         // This is clearer to read and understand from a code review aspect

         MethodYouWantDefaultsIn( SomeEnum.Name )

         // Than this ...

         MethodYouWantDefaultsIn( Params.DefaultValue )

    }

    public void MethodYouWantDefaultsIn( string name ) {

     

    }


  • Dwaine

    I personally dislike C++, but default param is definately one thing I miss.
    Problably some wrap-up llike C++ default params can be added to remedy the disadvantage.
  • wekempf

    Nice suggestion.
    However I don agree with your argument on readability and maintainability.

    The default values should comes with the signiture.
    In C++, they do it in the bloody but sometimes handy header files.
    For C#, they need to play some tricks. But if they can put a method signiture in an assembly, I guess they can put the default value in as well.

    There will be no such thing as  "no value". "default int" and "default float" etc are going to be replaced by actual value at compile time or linking time. It's doesn't change the fundamentals. If you decompile the resulting assembly, you can't tell weather default param was used or not.

    If default param was implemented, the vs intellisence probably would show the default value with the param name.


  • Some thoughts about default parameters for C#