Tech Junkie Blog - Real World Tutorials, Happy Coding!: C# : Automatically Implemented Properties

Thursday, March 26, 2015

C# : Automatically Implemented Properties

There are times when you see a class property without it's private member counterpart and all you see is the {set; get;} accessors. What you are looking at are auto properties that you can create  in C#, the only requirements is that the set; and get; accessors contains no logic.  Usually there are private members that the properties expose to other classes using the get/set accessors, like the code below:


    public class Product
    {
        private int productId;
        private string name;
        private string description;
        private decimal price;

        public int ProductId
        {
            get
            { return productId; }
            set
            {
                productId = value;
            }
        }

        public string Name
        {
            get
            { return name; }
            set
            {
                name = value;
            }
        }

        public string Description
        {
            get
            { return description; }
            set
            {
                description = value;
            }
        }

        public decimal Price
        {
            get
            { return price; }
            set
            {
                price = value;
            }
        }

    }

The above class uses the regular ways you define properties that are exposed to other classes. Even though there are only get/set properties. The auto implemented version of the class requires a lot less typing.
    public class Product
    {

        public int ProductId { get; set; }
        public string Name { get; set;}
        public string Description { get; set; }
        public decimal Price { get; set; }

    }
The properties do not have be define as a private member of the class. This pattern is called the field-backed property pattern. This means that the C# compiler will take care of the private members fields for us when we build our classes. The above example are mutable properties, meaning outside classes can change the values of the properties.



To create immutable properties, all you have to do is add the keyword private to the set; accessors. Immutable properties, means that the properties are only changeable within the class itself. Outside classes can only read the properties.
    public class Product
    {

        public int ProductId { get; private set; }
        public string Name { get; private set;}
        public string Description { private get; set; }
        public decimal Price { get; private set; }

    }

1 comment:

Search This Blog