Microsoft has launched Visual Studio 2015 preview version with .Net 4.6. If you haven’t downloaded it, download Visual Studio 2015 and .Net 4.6. Visual Studio 2015 has come with C# 6.0 with lots of new features which improve your coding style and standard.

So, today I am going to explain one of the feature of C# 6.0, how to set default values to auto property.

Before C# 6.0, developers used to set default value for property where properties have declared. Basically we used private variable to initialize or set default value of property. We use long code for a single property

Old Way
public class AutoPropertyNextProgrammingExample
{
        private string _employeeName = string.Empty;
        public AutoPropertyNextProgrammingExample()
        {
            EmployeeID = 10;
            Address = "New Delhi";
        }

        public int EmployeeID { get; set; }

        public string Address { get; set; }

        public string EmployeeName
        {

            get 
            {
                return _employeeName;
            }
            set
            {
                _employeeName = value;
            }
         }
 }

But time has been changed in C# 6.0, now you can initialize the default value when declare properties. Class automatically set the default value with properties when call the properties.

New Way in C# 6.0
public class AutoPropertyNextProgrammingExample
{
        public int EmployeeID { get; set; } = 10;
         
        //also write
        public int EmployeeID { get; } = 10;

        public string Address { get; set; } = "New Delhi";

        public string EmployeeName { get; set; }=string.Empty;
}

Some More Example

 public List<string> Roles { get; } = new List<string>() { "Admin", "SuperAdmin"};
public string Config { get; } = string.IsNullOrWhiteSpace(string connectionString =(string)Properties.Settings.Default.Context?["connectionString"])? connectionString : "<none>";
Conclusion:

So, Today we learned a new feature of C# 6.0 auto property set default value with visual studio 2015.

I hope this post will help you. Please put your feedback using comment which helps me to improve myself for next post. If you have any doubts please ask your doubts or query in the comment section and If you like this post, please share it with your friends. Thanks