Read/Write-Only Properties
Part of the Object Oriented Programming section of Coddy's C# journey — lesson 11 of 70.
Sometimes you need properties that can only be read or only be written. You can control this by using private on individual accessors.
A read-only property has a public getter but a private setter (or no setter at all):
public class User
{
public string Username { get; private set; }
public User(string username)
{
Username = username;
}
}External code can read Username, but only the class itself can modify it. This is useful for values that should be set once during construction.
A write-only property has a public setter but a private getter:
public class Account
{
public string Password { private get; set; }
public bool ValidatePassword(string input)
{
return input == Password;
}
}Write-only properties are rare but useful for sensitive data like passwords, where you want to accept input without exposing the stored value.
You can also create truly read-only properties with only a getter:
public class Circle
{
public double Radius { get; }
public double Area => Math.PI * Radius * Radius;
public Circle(double radius)
{
Radius = radius;
}
}Properties with only get; can only be assigned in the constructor or at declaration, making them immutable after object creation.
Challenge
EasyLet's build a secure configuration system that demonstrates when to use read-only and write-only properties to protect sensitive data.
You'll create two files to organize your code:
Config.cs: Define aServerConfigclass in theSettingsnamespace that manages server configuration. It should have:- A read-only property
ServerName(can only be set in the constructor) - A read-only property
Portwith a private setter (set via constructor) - A write-only property
ApiKeythat stores a secret key internally - A method
ValidateApiKey(string key)that returnstrueif the provided key matches the stored one - A constructor that accepts the server name and port
- A read-only property
Program.cs: In your main file, create aServerConfigobject using input values, set the API key, then validate it against a test key.
You will receive four inputs:
- Server name
- Port number
- API key to store
- API key to validate
Print the server details and validation result in this format:
Server: {ServerName}, Port: {Port}
API Key Valid: {True/False}For example, if the inputs are MainServer, 8080, secret123, and secret123, the output should be:
Server: MainServer, Port: 8080
API Key Valid: TrueCheat sheet
You can control property access by using private on individual accessors.
Read-only property with a private setter:
public class User
{
public string Username { get; private set; }
public User(string username)
{
Username = username;
}
}External code can read Username, but only the class itself can modify it.
Write-only property with a private getter:
public class Account
{
public string Password { private get; set; }
public bool ValidatePassword(string input)
{
return input == Password;
}
}Useful for sensitive data where you want to accept input without exposing the stored value.
Truly read-only property with only a getter:
public class Circle
{
public double Radius { get; }
public Circle(double radius)
{
Radius = radius;
}
}Properties with only get; can only be assigned in the constructor or at declaration, making them immutable after object creation.
Try it yourself
using System;
using Settings;
class Program
{
public static void Main(string[] args)
{
// Read inputs
string serverName = Console.ReadLine();
int port = Convert.ToInt32(Console.ReadLine());
string apiKeyToStore = Console.ReadLine();
string apiKeyToValidate = Console.ReadLine();
// TODO: Create a ServerConfig object with serverName and port
// TODO: Set the API key using the write-only property
// TODO: Validate the API key and print the results
// Format: Server: {ServerName}, Port: {Port}
// API Key Valid: {True/False}
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesNamespaces & DirectivesIntro to Classes & ObjectsThe 'this' KeywordMethods and ParametersFields vs PropertiesConstructorsObject InitializersRecap - Simple Calculator4Inheritance
Basic Inheritance (:) SyntaxThe 'base' KeywordVirtual & Override KeywordsSealed ClassesThe 'object' Base ClassRecap - Employee Hierarchy7Advanced Features
Operator OverloadingIndexers (this[])ToString() OverrideExtension MethodsRecap - Custom List2Properties & Static Members
Auto-Implemented PropertiesRead/Write-Only PropertiesStatic Fields & MethodsStatic ClassesExpression-Bodied Members5Polymorphism & Interfaces
Compile vs Runtime PolyInterface vs Abstract ClassMultiple InterfacesExplicit InterfacesUpcasting & DowncastingRecap - Shape Calculator