Reputation:
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?
Upvotes: 2
Views: 645
Reputation: 292
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.
Upvotes: 0
Reputation: 14956
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.
Upvotes: 0
Reputation: 1064224
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.
Upvotes: 2
Reputation: 5779
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.
Upvotes: 0
Reputation: 755577
This is more of a style question than anything else. There are only a few cases where it is a functional issue
Upvotes: 8
Reputation: 42326
depends on when you want it to be set...
private int _id = -1
will initialize _id before the constructor is called.
Upvotes: 2
Reputation: 156055
Setting it "inline" rather than using the constructor seems, to me, to indicate intention better. Functionally they're the same.
Upvotes: 0