Monday, August 24, 2020

Properties

  •  A property is a class member that encapsulate a getter/setter for accessing a filed.  
  • As a best practice, we must declare fields as private and create public properties to provide access to them. 
  • A property encapsulates a get and a set method.
  •     public class Customer
        {
            private string _name;
            public string Name
            {
                get { return _name; }
                set { _name = value; }
            }
        }
    
  • Inside the get/set methods we can have some logic.
  •     public class Person
        {
            public DateTime BirthDate { get; set; }
            public int Age
            {
                get
                {
                    var timespan = DateTime.Today - BirthDate;
                    var years = timespan.Days / 365;
                    return years;
                }
            }
        }
    
  • If you don’t need to write any specific logic in the get or set method, it’s more efficient to create an auto-implemented property. An auto-implemented property encapsulates a private field behind the scene. So you don’t need to manually create one. The compiler creates one for you.
  •     public class Person
        {
            public DateTime BirthDate { get; set; }
        }
    
  • Auto-implemented properties are required to specify both get and set, so if you want an auto-implemented property to be read-only, you must use private setters. 
  •     public class Person
        {
            public DateTime BirthDate { get; private set; }
        }
    

No comments:

Post a Comment