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

CsharpServer Side ProgrammingProgramming

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
raja
Published on 04-Aug-2020 06:54:46
Advertisements