Get Set in C# – Master Access Specifiers Easily!
Hey there, coder! 👋 Have you ever wondered how to control access to your class properties in C#? 🤔
That’s exactly where Get Set in C# comes into play! It helps you encapsulate data and ensure security and control over how properties are accessed and modified.
By the end of this lesson, you’ll be a pro at using Get and Set accessors in C# with real-world examples and hands-on coding! So, grab your coffee ☕, and let’s dive in! 🚀
📚 What You Will Learn in This Lesson
✔️ What Get Set in C# means and why it’s important.
✔️ How Get and Set accessors work in C#.
✔️ The difference between Get Set in C# and Destructors (~).
✔️ The syntax and real-world usage.
✔️ Multiple coding examples with explanations and outputs.
✔️ Why it is needed and where it is used in the real world.
🤔 What is Get Set in C#?
Get and Set are accessors used to read and modify private fields inside a class. This is part of Encapsulation, which helps in hiding sensitive data and only allowing controlled access.
Let’s compare Get Set in C# with Destructors (~) to understand the difference:
| Feature | Get Set in C# | Destructors (~) |
|---|---|---|
| Purpose | Controls property access | Cleans up resources |
| When Used? | During object lifecycle | When an object is destroyed |
| Manual Control? | Yes | No (handled by Garbage Collector) |
| Example | Setting a name for a student | Releasing database connections |
Now that you get the idea, let’s look at the syntax! 👇
🛠️ Syntax of Get Set in C#
class ClassName
{
private datatype variableName; // Private field
public datatype PropertyName
{
get { return variableName; } // Getter
set { variableName = value; } // Setter
}
}
get→ Used to retrieve the value of a private field.set→ Used to assign a value to the private field.
💡 Example 1: Basic Get Set in C#
Let’s see a simple example where we set and get a person’s name!
using System;
class Person
{
private string name; // Private field
public string Name
{
get { return name; } // Getter
set { name = value; } // Setter
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.Name = "Alice"; // Using Set
Console.WriteLine("Hello, " + p.Name); // Using Get
}
}
📌 Output:
Hello, Alice
🛠️ Code Explanation:
✅ We created a private field name.
✅ Used get to retrieve the value.
✅ Used set to assign a value.
✅ Set Name = "Alice" and printed it.
Nice and easy, right? Now, let’s add some validation!
📝 Example 2: Adding Validation with Set
We don’t want anyone to set an empty name! Let’s fix that.
using System;
class Person
{
private string name;
public string Name
{
get { return name; }
set
{
if (string.IsNullOrWhiteSpace(value))
Console.WriteLine("Name cannot be empty!");
else
name = value;
}
}
}
class Program
{
static void Main()
{
Person p = new Person();
p.Name = ""; // Invalid input
p.Name = "Bob"; // Valid input
Console.WriteLine("Hello, " + p.Name);
}
}
📌 Output:
Name cannot be empty!
Hello, Bob
✅ Now, if someone tries to set an empty name, it won’t work! 🚀
🌍 Real-World Example – Bank Account System
Imagine a Bank Account where we must ensure the balance cannot be negative. Let’s use Get Set in C# to enforce this rule!
using System;
class BankAccount
{
private double balance;
public double Balance
{
get { return balance; } // Get balance
set
{
if (value >= 0)
balance = value; // Set new balance
else
Console.WriteLine("Balance cannot be negative!");
}
}
}
class Program
{
static void Main()
{
BankAccount account = new BankAccount();
account.Balance = 500; // Valid balance
Console.WriteLine("Current Balance: " + account.Balance);
account.Balance = -100; // Invalid balance
}
}
📌 Output:
Current Balance: 500
Balance cannot be negative!
✅ This is why Get Set in C# is super useful! It ensures data integrity while keeping things secure and flexible.
🔄 Auto-Implemented Properties (Shorter Way!)
C# allows a shortcut for properties without manually defining a private field.
class Car
{
public string Model { get; set; } // Auto-implemented property
}
class Program
{
static void Main()
{
Car myCar = new Car();
myCar.Model = "Tesla";
Console.WriteLine("Car Model: " + myCar.Model);
}
}
📌 Output:
Car Model: Tesla
✅ This saves time and keeps your code clean!
🎯 Why is Get Set in C# Important?
✅ Encapsulation – Keeps fields private but still accessible.
✅ Validation – Prevents invalid data entry.
✅ Flexibility – You can modify property behavior without affecting the class.
✨ Conclusions
✅ Get Set in C# helps you control how data is accessed.
✅ It prevents invalid data and ensures security.
✅ Real-world scenarios like banking and user data handling use this concept every day!
✅ It’s way different from Destructors (~), which clean up resources instead of managing data.
Next What? 🤔
You’re now a pro at Get Set in C#! 🎉 But what’s next?
In the next chapter, we’ll explore Abstraction in C# – a powerful way to hide complex details and focus on what matters! Stay tuned! 🚀
Now, go ahead and practice some Get Set magic in your code! 💻✨
