I recently started learning C# and just reached the topic of ‘Properties’.
I understand the ‘old’ way of using a private field with an extra getter and setter function is a bit cumbersome and ‘ugly’.
CarWithFields carWithFields = new CarWithFields();
carWithFields.setPrice(100);
Console.WriteLine(carWithFields.getPrice());
class CarWithFields
{
private int _price;
public int getPrice()
{
return _price;
}
public void setPrice(int value)
{
_price = value;
}
};
Achieving the same thing with properties is much cleaner.
CarWithProperties carWithProperties = new CarWithProperties();
carWithProperties.Price = 100;
Console.WriteLine(carWithProperties.Price);
class CarWithProperties
{
public int Price { get; set; }
}
However I have seen quite a lot of examples where both are used at the same time, with the property being used as a sort of ‘wrapper’ around the field?
CarWithBoth carWithBoth = new CarWithBoth();
carWithBoth.Price = 100;
Console.WriteLine(carWithBoth.Price);
class CarWithBoth
{
private int _price;
public int Price
{
get
{
return _price;
}
set
{
_price = value;
}
}
}
I guess the third solution still looks better and cleaner than the first solution, but at that point why not just solely use a property? Is there any benefit to mixing these two approaches like this?
Thank you!
Orluca is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.