When you execute the above c# program, we will get a result like as shown below. If you observe the above example, we created properties with get and set accessors without having any logic implementation. Generally, the auto-implemented properties are useful whenever there is no logic implementation required in property accessors.įollowing is the example of creating auto-implemented properties in the c# programming language. In c#, a property is called an auto-implemented property when it contains accessors ( get, set) without having any logic implementation. This is how we can create write-only properties in c# applications based on our requirements. If we uncomment the commented code, then we will get a compile error because our Name property doesn’t contain any get accessor to return a value. If you observe the above example, we created properties using only set accessor to make the properties are write-only based on our requirements. C# Create Write Only PropertiesĪs discussed, if a property contains the only set accessor, then we will call it a write-only property. Following is the example of creating write-only properties in the c# programming language.Ĭonsole.WriteLine("Location: " + location) This is how we can create read-only properties in c# applications based on our requirements. When you execute the above c# program, you will get a result like as shown below. If we uncomment the commented code, we will get a compile error because our Name property doesn’t contain any set accessor to set a new value. If you observe the above example, we created properties using only get accessor to make the properties are read-only based on our requirements. User u = new User("Suresh Dasari", "Hyderabad") C# Create Read-Only PropertiesĪs discussed, if a property contains the only get accessor, then we will call it a read-only property. Following is the example of creating read-only properties in the c# programming language. If you observe the above example, our variable text converted to upper case, and even after we set variable text as “ Rohini”, it displayed text as “ Suresh Dasari” because of the set accessor validation fails in the property.
When you execute the above c# program, we will get the result as shown below. If you observe the above example, we are extending the behavior of private variables ( name, location) using properties ( Name, Location) with get and set accessors by performing some validations like to make sure Name value equals to only “ Suresh” using set accessor and converting property text to uppercase with get accessor.
Console.WriteLine("Location: " + u.Location) Ĭonsole.WriteLine("\nPress Enter Key to Exit.")