C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
C# Default values for getter-only propertiesThis feature allows us to set default values for the getters. The getter-only property is read-only property. We can't set a new value to this property. Compiler reports an error: cannot be assigned at compile time, if we assign value explicitly. C# Default value for getter-only property Example 1using System; namespace CSharpFeatures { class Student { public string Name { get; } = "Rahul kumar"; public string Email { get; } = "rahul@abc.com"; } public class PropertyInitializer { public static void Main(string[] args) { Student student = new Student(); Console.WriteLine(student.Name); Console.WriteLine(student.Email); } } } Output Rahul kumar [email protected] Let's see an example, what happen if we assign value explicitly. C# Default value for getter-only property Example 2using System; namespace CSharpFeatures { class Student { public string Name { get; } = "Rahul kumar"; public string Email { get; } = "rahul@abc.com"; } public class PropertyInitializer { public static void Main(string[] args) { Student student = new Student(); Console.WriteLine(student.Name); Console.WriteLine(student.Email); student.Name = "john"; Console.WriteLine(student.Name); } } } Output error CS0200: Property or indexer 'Student.Name' cannot be assigned to -- it is read only
Next TopicC# Expression Bodied Members
|