Reputation: 23
What is the best practice in C# for class members with default non-zero values?
You can write it this way:
private int someField = 9;
public int SomeField
{
get ( return someField; }
set { someField = value; }
}
Or this way:
public Int32 SomeField = 9;
But Int32 is identical to int.
So, which way is better and may cause less problems?
Upvotes: 0
Views: 141
Reputation: 2771
As a best practice I would avoid hard coding values like this. They can be really tricky to maintain later. You best bet is to create an enumerated list in a centralized place and cast those to Integers. This allows for better control / maintenance moving forward.
public enum SomeFieldValue
{
ValueOne = 1,
ValueTwo = 2,
ValueThree = 3
}
public int MyDefaultSomeValue = (int) SomeFieldValue.ValueOne;
Upvotes: 0
Reputation: 3360
Alternative to the answer proposed by @Oded:
public int field1 { get; set; } //auto-implemented property, :)
public MyClass() {
field1 = 9; //or other default value
}
Upvotes: 1
Reputation: 8116
Also note that if you have multiple constructors, don't explicitly initialize fields in their declaration. Because the compiler generates code to initialize those fields for each constructor. For that situation, use one base constructor which initializes your fields and having the other constructors call this base constructor.
int field1;
int field2;
int field3;
public MyClass()
{
field1 = 12;
field2 = 1;
field3 = 5;
}
public MyClass(int SomeValue) : this()
{
field1 = SomeValue;
}
public MyClass(int SomeValue, int SomeOtherValue) : this()
{
field1 = SomeValue;
field2 = SomeOtherValue;
}
Upvotes: 0
Reputation: 498904
Just use the C# aliases, they are shorter to read and are there for that reason.
You should not expose fields as public
- you are breaking encapsulation this way.
In short, use:
private int someField = 9;
public int SomeField
{
get ( return someField; }
set { someField = value; }
}
Upvotes: 6