What are the differences between a property and a variable?

  • Variables can't be declared in interfaces and force to be implemented. Whereas Properties can be declared and enforced.
  • Fields can't be serialized, properties are the media used for serializing and deserializing object contents
  • Properties can provide business logic or validations before assigning to variables inside a class.
  • In a general practice, a class contains one or more private fields (variables) which are wrapped around by public properties.
class Car
    {
        private string _id;

        public string Id
        {
            get
            {
                return _id;
            }

            set
            {
                if (value.Length < 10)
                {
                    throw new InvalidOperationException("ID Can't be Less than 10 CHARS");
                }
                else
                {
                    _id = value;
                }
            }
        }
    }
  • Variables can’t be declared in interfaces and force to be implemented. Whereas Properties can be declared and enforced.
  • Fields can’t be serialized, properties are the media used for serializing and deserializing object contents
  • Properties can provide business logic or validations before assigning to variables inside a class.
  • In a general practice, a class contains one or more private fields (variables) which are wrapped around by public properties.
class Car
    {
        private string _id;

        public string Id
        {
            get
            {
                return _id;
            }

            set
            {
                if (value.Length < 10)
                {
                    throw new InvalidOperationException("ID Can't be Less than 10 CHARS");
                }
                else
                {
                    _id = value;
                }
            }
        }
    }
Sriram Mannava
Sriram Mannava

I'm a full-stack developer and a software enthusiast who likes to play around with cloud and tech stack out of curiosity.

Leave a Reply

Your email address will not be published. Required fields are marked *