Valerie Meunier

Valerie Meunier

  • NA
  • 693
  • 82.9k

data encapsulation without properties?

Jun 8 2022 2:18 PM

Hi

i read a lot about data encapsulation, using properties etc... I tried to do data encapsulation without properties like this and this works:

My question is: why should i use properties? What are the advantages of properties compared to my code? Is this good pratice?

Thanks.

V

using System;
   public class Version1
    {
        private int x;
        public int GetX()
        {
            return x;
        }

        public void SetX(int x)
        {
            if (x > 0)
                this.x = x;
            else
Console.WriteLine("Must be >0");
        }
    }
    
  class See
    {
        public static void Main()
        {
          Version1 e = new Version1();
          e.SetX(10);
          Console.WriteLine(e.GetX());
          e.SetX(-50);
        }
    }
 


Answers (2)