0
0
C Sharp (C#)programming~30 mins

Read-only and write-only properties in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Read-only and Write-only Properties in C#
📖 Scenario: You are creating a simple user profile system where some information should be visible but not changeable, and some information should be set but not visible directly.
🎯 Goal: Build a C# class with a read-only property and a write-only property to control access to user data.
📋 What You'll Learn
Create a class called UserProfile
Add a private string field called username
Add a private string field called password
Create a read-only property Username that returns the username
Create a write-only property Password that sets the password
Create a method DisplayInfo that prints the username and a message about the password
💡 Why This Matters
🌍 Real World
Read-only and write-only properties are used in real applications to protect sensitive data like usernames and passwords, ensuring users can see or set data only in allowed ways.
💼 Career
Understanding property access control is important for software developers to write secure and maintainable code, especially when handling user data.
Progress0 / 4 steps
1
Create the UserProfile class with private fields
Create a class called UserProfile with two private string fields: username and password. Initialize username to "Alice" and password to "" (empty string).
C Sharp (C#)
Need a hint?

Use private string username = "Alice"; and private string password = ""; inside the class.

2
Add read-only and write-only properties
Inside the UserProfile class, add a read-only property called Username that returns the username field, and a write-only property called Password that sets the password field.
C Sharp (C#)
Need a hint?

Use public string Username { get { return username; } } and public string Password { set { password = value; } }.

3
Add a method to display user info
Add a public method called DisplayInfo inside UserProfile that prints the username and the message "Password is set" if the password is not empty, otherwise "Password is not set".
C Sharp (C#)
Need a hint?

Use System.Console.WriteLine to print the username and check if password is empty or not.

4
Create an instance, set password, and display info
In the Main method, create an instance of UserProfile called user. Set the Password property to "secret123". Then call DisplayInfo() on user to print the username and password status.
C Sharp (C#)
Need a hint?

Create UserProfile user = new UserProfile();, set user.Password = "secret123";, then call user.DisplayInfo();.