views:

209

answers:

7

Hi,

If you have an object like this:

public class Foo
{
 private int _id;

 public int id
 {
  get { return _id; }
  set { _id = value; }
 }

 private string _name;

 public string name
 {
  get { return _name; }
  set { _name = value; }
 }
}

And you want to initialize id to -1 and name to String.Empty what is the best practice? (and why)

Doing:

private int _id = -1

Or

Setting _id = -1 and name = String.Empty in the constructor?

Kind regards,

sem

A: 

Setting it "inline" rather than using the constructor seems, to me, to indicate intention better. Functionally they're the same.

bdukes
+2  A: 

depends on when you want it to be set...

private int _id = -1

will initialize _id before the constructor is called.

m_oLogin
+7  A: 

This is more of a style question than anything else. There are only a few cases where it is a functional issue

  1. When you have many constructors which all initialize the fields to the same value. At that point you have redundant code and should either refactor your constructors or use field initializers.
  2. Don't use a field initializer if it depends on the value of another field in the same class hierarchy. In the abscence of partial classes the outcome is predictable but still can throw people for a loop..
JaredPar
I agree that this is mostly a stylistic thing. The most important consideration is being consistent about which approach you use throughout your app.
JohnFx
@JohnFx, actually I think getting the group to agree is the most important. ;)
JaredPar
A: 

A CLR wizard might correct me, but I believe those two approaches are functionally identical, but you could make an argument that setting the default values in the constructor is more explicit and obvious, but also a bit messier.

Matt Peterson
+2  A: 

The field approach is concise, which gets a lot of votes, but my preference (for simple properties) would be to use auto-properties, in which case you are forced to use the constructor:

    public Foo() {
        Id = -1;
        Name = "";
    }
    public int Id {get;set;}
    public string Name {get;set;}

You might also consider using [DefaultValue(-1)] etc, which helps designers and serializers, but this does not affect the initial value of an auto implemented property (or a regular property) - it is additional info only.

Marc Gravell
true with easy objects, my object is quite more complex but I just wanted to set an example.
Sem Dendoncker
A: 

Inline initialization is added to the top of the constructor by the C# compiler so there is really no difference. Personally I prefer always adding constructors even if it is only a default constructor.

Jakob Christensen
A: 

It's mainly the question of style preference. I usually assign them in the constructor, because it is a sane place for all the data and procedures that take place when object is instantiated.

aks