Reputation: 7809
Note that the following code is in a class a single class
private string _fee;
private string _receipt;
public string Fee
{
get { return _fee; }
private set { _fee = value; }
}
public string Receipt
{
get { return _receipt; }
private set { _receipt = value;}
}
public MyValue(string fee, string receipt) : this()
{
_fee = int.Parse(receipt).ToString();
_receipt = receipt;
}
As you can see my property does nothing so should I use
_fee = int.Parse(fee).ToString();
_receipt = receipt;
or
Fee = int.Parse(fee).ToString();
Receipt = receipt;
Upvotes: 3
Views: 1489
Reputation: 15533
I would always use the members directly.
This is because you may implement code in the setter that isn't able to run correctly from within the constructor because some other fields aren't initialized.
It may become even worse if the properties are virtual as womp mentioned.
Upvotes: 0
Reputation: 116987
In this case it doesn't matter, as long as you're consistent throughout your code.
If, however, your properties were marked as virtual
, then it wouldn't be a good idea to access them in your constructor, and it would be better to use the fields directly. This is because the behaviour of your properties could be overridden, and your base class could potentially call into breaking code.
Edit: Just to clarify, I'm just referring to differences in the approach for the OP's example. marc_s gives some great points as to why properties can be advantageous for most situations.
Upvotes: 4
Reputation: 10307
Use the properties, and if you're on C# 3 you should use automatically implemented properties like this:
public string Fee
{
get; private set;
}
public string Receipt
{
get; private set;
}
public MyValue(string fee, string receipt) : this()
{
this.Fee = int.Parse(fee).ToString();
this.Receipt = receipt;
}
Upvotes: 16
Reputation: 755381
I would always use properties - it gives you more flexibility:
Also, it seems that .NET reflection behaves slightly differently on properties vs. fields, so if you have a mix of properties and fields, you need to know about those subtle differences - if you use only properties, you're good to go :-)
While inside the class, you can use either the backing store field, or the property - if you use the property, any side-effects your setter might have (updating other fields, logging your call etc.) will be used - if you access the backing store field directly, you get around those. This can be a good or a bad thing - depends on your scenario. Just be aware of what you're doing! :-)
Marc
Upvotes: 10