0

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?

Bugaboo
  • 973
  • 1
  • 17
  • 36
  • Properties are good because they shelter you from later changes. Lets say later that you want XYZ to mean the same thing but its represented differently, or you need to do some sort of hook when someone sets something. Without a property you have screwed yourself since you break dependent code – devshorts Feb 14 '14 at 00:57

2 Answers2

5

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)

Simon Whitehead
  • 63,300
  • 9
  • 114
  • 138
  • Also note: when you go to release mode and don't have a debugger attached, the compiler will most likely inline property calls that do not do any extra steps and turn it in to a field call if there is no reason not to. – Scott Chamberlain Feb 14 '14 at 01:03
  • Indeed, automatic properties are inlined, at least in the 64-bit JIT that I have tested. – Simon Whitehead Feb 14 '14 at 01:04
0

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.

Rafa Paez
  • 4,820
  • 18
  • 35