Complete C# Tutorial

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 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:

FeatureGet Set in C#Destructors (~)
PurposeControls property accessCleans up resources
When Used?During object lifecycleWhen an object is destroyed
Manual Control?YesNo (handled by Garbage Collector)
ExampleSetting a name for a studentReleasing 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! πŸ’»βœ¨

Leave a Comment

Share this Doc

GET SET

Or copy link