If I have a class as follows:
class A
{
private int _xyz;
public int XYZ
{
get { return _xyz; }
set { _xyz = value; }
}
}
Is there any use in defining a property or does it make sense to just make '_xyz' public?
If I have a class as follows:
class A
{
private int _xyz;
public int XYZ
{
get { return _xyz; }
set { _xyz = value; }
}
}
Is there any use in defining a property or does it make sense to just make '_xyz' public?
Properties allow you to change the implementation later without breaking the public facing API of the class.
Your current property has no special purpose, so you can make it an automatic property:
public int XYZ { get; set; }
This gives you a property that you can change later (if needed) without breaking the type.
For example, later you might want to log that the property changed (bad example, but you get the idea):
private int _xyz;
public int XYZ
{
get { return _xyz; }
set { _
xyz = value;
_logger.Log("Changed XYZ");
}
}
This won't break any other code and doesn't require any re-compilation of other assemblies that depend on this type.
(Logging a property change is a bad example, because you probably don't want to log property changes, especially if they change frequently. This is for demonstration purposes only)
In a Class, it is a good practice in OOP to use encapsulation even if at the moment being you are not going to check anything in the getters or setters (properties).
Anyway, if you have a class with only a member of type int and no behavior at all I will recommend you to use a Struct instead of a Class. According to the MSDN documentation:
In general, classes are used to model more complex behavior, or data that is intended to be modified after a class object is created. Structs are best suited for small data structures that contain primarily data that is not intended to be modified after the struct is created.
I would say that Classes (Objects) are meant to have a Behavior while Structs are meant to have data. When designing Classes think about Messages (properties and methods) rather than fields of data.