5

I have seen a lot of code like this:

class A 
{
    public string a;
    public string b;
    public int c;
    public int d;

    public A (string a = "something", string b = "something", int c = 123, int d = 456) 
    {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
}

which in my opinion abuses optional parameters. Wouldn't it be better to just make the constructor like this:

public A() 
{
    this.a = "something";
    this.b = "something";
    this.c = 123;
    this.d = 456;
}

and later on the user can do something like this:

A a = new A() { a = "myString", c = 1000 };

?

Is there any particular reason that makes the first version of the constructor better than the second version?

Rufus L
  • 36,127
  • 5
  • 30
  • 43
Chin
  • 19,717
  • 37
  • 107
  • 164
  • 1
    I think that it has been already discussed in relation to methods - http://stackoverflow.com/questions/251868/should-you-declare-methods-using-overloads-or-optional-parameters-in-c-sharp-4-0. And constructors are just special methods, so it applies to them as well. – Eugene Podskal Mar 26 '15 at 18:42
  • 2
    Not if you want to be immutable. – SLaks Mar 26 '15 at 18:43
  • @FrédéricHamidi: [Wrong](http://tryroslyn.azurewebsites.net/#f:s/K4Zwlgdg5gBAygTxAFwKYFsDcAoADsAIwBswBjGUogQxBBgGEYBvbGNmSZGADx3ZnzEyMAG4B7MABMYAWQAUASmat+7CKgDuDJtwC8AJgC+fdoeyGgA=) – SLaks Mar 26 '15 at 18:44
  • Who says it's an abuse? It's shorthand for "hey, instantiator, you got some defaults for me? No? K, using mine." Easier than, say, taking in an int?, checking it for null, then using the default value. –  Mar 26 '15 at 18:46
  • Exposing public fields falls mostly in the "bad" category. Giving the client programmer a chance to forget to set a required property is also "bad". – Hans Passant Mar 26 '15 at 18:48
  • @FrédéricHamidi: I'm pretty sure not. Check the spec. – SLaks Mar 26 '15 at 18:50
  • @SLaks, you're right, the documentation does say *accessible fields or properties*. I stand corrected. – Frédéric Hamidi Mar 26 '15 at 18:51
  • @HansPassant , SLaks - (semi-meta) Not trying to imply anything, genuinely curious about this type of question and you are both outstanding members of the community. Did you post a comment as opposed to an answer because you felt this question would be closed, or because you generally didn't feel the question warranted an answer? I am curious if these types of narrowly scoped opinion based questions are missed opportunities to pass on wisdom in the form of narrowly scoped answers with a small set of best practice scenarios suggested or explained. – Travis J Mar 26 '15 at 19:04
  • @TravisJ: Because that one sentence is too small for an answer. – SLaks Mar 26 '15 at 19:06
  • He asked the wrong question. – Hans Passant Mar 26 '15 at 19:14

0 Answers0