How do you give a C# Auto-Property a default value?


In C# 5.0 and before to give an value to the Auto Property we have to do in the constructor

The constructor will be automatically called when class is instantiated and the value will be set

After C#5.0 a new way to give a value to auto property has come which is similar in assigning a value to the variable

Example

Set Value in Constructor
class Demo{
   public Demo(){
      FirstName = "DemoName";
   }
   public string FirstName { get; set; }
}
class Program{
   static void Main(){
      Demo obj = new Demo();
      System.Console.WriteLine(obj.FirstName);
      Console.ReadLine();
   }
}

Output

DemoName

C# 6.0 Example

class Demo{
   public string FirstName { get; set; } = "DemoName";
}
class Program{
   static void Main(){
      Demo obj = new Demo();
      System.Console.WriteLine(obj.FirstName);
      Console.ReadLine();
   }
}

Output

DemoName

Updated on: 04-Aug-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements