Search code examples
c#propertiesgetsetencapsulation

c# encapsulation Get/ Set


looking for some clarification on Get / Set. I have this code which I use to create my objects..However I want to have some validation in with the length and width (both need to be greater than some number as example). I believe Get / Set is the way to go and I have used this when changing fields in an instance - but how do I do it at the Instantiation stage?

class Room
{
    public Double dblLength;
    public Double dblWidth;

    public Room (Double _dblLength, Double _dblWidth)
    {

        dblLength = _dblLength;
        dblWidth = _dblWidth;
    }

Solution

  • Turn fields into properties; implement validation within corresponding set:

    class Room
    {
        private Double m_DblLength;
        private Double m_DblWidth;
    
        public Room (Double _dblLength, Double _dblWidth) {
          DblLength = _dblLength;
          DblWidth = _dblWidth;
        }
    
        public Double DblLength {
          get {
            return m_DblLength;
          }
          set {
            //TODO: validation here
            if (value < 0)
              throw new ArgumentOutOfRangeException("value"); 
    
            m_DblLength = value;
          }
        }
    
        public Double DblWidth {
          get {
            return m_DblWidth;
          }
          set {
            //TODO: validation here
            if (value < 0)
              throw new ArgumentOutOfRangeException("value"); 
    
            m_DblWidth = value;
          }
        }