How do you give a C# Auto-Property a default value?
https://www.tutorialspoint.com/how-do-you-give-a-chash-auto-property-a-default-value
-
12-09-2020 - |
Question
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
Advertisements
Not affiliated with Tutorialspoint