Properties let you control how data is accessed or changed in a class. Read-only properties let you see data but not change it. Write-only properties let you change data but not see it.
0
0
Read-only and write-only properties in C Sharp (C#)
Introduction
When you want to allow users to get a value but not change it, like a person's age.
When you want to let users set a value but keep it hidden, like a password.
When you want to protect important data from accidental changes.
When you want to control how data is updated or retrieved with extra logic.
When you want to keep some data private but still allow limited access.
Syntax
C Sharp (C#)
public class MyClass { // Read-only property public int ReadOnlyProperty { get; } // Write-only property private int _writeOnlyField; public int WriteOnlyProperty { set { _writeOnlyField = value; } } }
A read-only property has only a get accessor.
A write-only property has only a set accessor.
Examples
This class lets you read the age but not change it after creation.
C Sharp (C#)
public class Person { private int _age; // Read-only property public int Age { get { return _age; } } public Person(int age) { _age = age; } }
This class lets you set the password but not read it back.
C Sharp (C#)
public class Secret { private string _password; // Write-only property public string Password { set { _password = value; } } }
Shows a short way to write a read-only property and a write-only property.
C Sharp (C#)
public class Example { private int _value; // Read-only property with expression body public int Value => _value; // Write-only property public int SetValue { set { _value = value; } } }
Sample Program
This program creates a person with an age you can read but a password you can only set. It shows how read-only and write-only properties work.
C Sharp (C#)
using System; public class Person { private int _age; private string _password; // Read-only property public int Age { get { return _age; } } // Write-only property public string Password { set { _password = value; } } public Person(int age) { _age = age; } public void ShowPassword() { Console.WriteLine("Password is hidden and cannot be read directly."); } } class Program { static void Main() { Person p = new Person(30); Console.WriteLine($"Age: {p.Age}"); p.Password = "mySecret123"; p.ShowPassword(); // The following line would cause a compile error because Password has no get accessor // Console.WriteLine(p.Password); } }
OutputSuccess
Important Notes
Trying to read a write-only property or write to a read-only property will cause a compile error.
Read-only properties are useful for data you want to protect from changes after setting.
Write-only properties are rare but useful for sensitive data like passwords.
Summary
Read-only properties have only a get accessor to allow reading but not writing.
Write-only properties have only a set accessor to allow writing but not reading.
They help control how data is accessed and protect sensitive information.