Properties and Methods: Encapsulating Behaviour in C#

Control how your objects behave and protect their internal state

Encapsulation is a core principle of OOP. It means bundling data (fields/properties) and behaviour (methods) together, and restricting direct access to internal details. In C#, we use properties and methods to do this.

Let’s break it down with a class-based example and see how it applies in your WinForms apps.


🧱 What Is Encapsulation?

Encapsulation means:

  • Hiding internal fields from outside interference
  • Exposing only what’s needed through public properties or methods
  • Protecting object integrity with logic and validation

βœ… Helps prevent bugs
βœ… Makes classes easier to understand and use
βœ… Allows internal changes without breaking outside code


πŸ‘©β€πŸ« Example: Student Class

public class Student
{
    // Private field (hidden from outside)
    private int _age;

    // Public property (controlled access)
    public int Age
    {
        get { return _age; }
        set
        {
            if (value >= 0)
                _age = value;
            else
                throw new ArgumentException("Age cannot be negative.");
        }
    }

    // Method (encapsulated behaviour)
    public string Describe()
    {
        return $"This student is {_age} years old.";
    }
}

βœ… Benefits of Using Properties

Properties are the bridge between fields and the outside world. They allow:

  • Validation (e.g. preventing bad data)
  • Read-only or write-only access
  • Calculated values (e.g. IsAdult => Age >= 18)

πŸ” Read-Only Example

public string FullName { get; } = "Alice Johnson";

✨ Adding Methods to Represent Actions

Methods represent what the object can do β€” its behaviour.

public class Cat
{
    public string Name { get; set; }

    public string Meow()
    {
        return $"{Name} says: Meow!";
    }

    public void Eat(string food)
    {
        Console.WriteLine($"{Name} eats {food}.");
    }
}

Use these methods in WinForms to display info or update the UI.


πŸ§ͺ WinForms Example

Cat myCat = new Cat { Name = "Luna" };

MessageBox.Show(myCat.Meow());

Encapsulation means you never directly change internal variables like sound = "meow" β€” you ask the cat to Meow() instead.


🧠 Properties vs Methods

Use When…PropertyMethod
Represents data/stateβœ… Yes❌ Not ideal
Represents an action❌ Noβœ… Yes
May involve logic/validationβœ… Oftenβœ… Often
You expect a return valueβœ… (for simple values)βœ… (for complex logic or action)

πŸ“š Summary

FeaturePurposeExample
Private fieldStores internal dataprivate int _age;
PropertySafely access or modify datapublic int Age { get; set; }
MethodPerform logic or actionspublic void Meow()

βœ… Use properties for access, methods for action


βœ… Best Practices

  • βœ… Use private fields for internal storage
  • βœ… Use public properties for controlled access
  • βœ… Add validation in set to enforce rules
  • βœ… Use methods for meaningful actions (not just setting data)
  • βœ… Use PascalCase for property and method names

πŸ§ͺ Quick Challenge

🧩 Create a BankAccount class with:

  • Balance (read-only property)
  • Deposit(decimal amount) method
  • Withdraw(decimal amount) method that prevents overdraft

Try calling these from a WinForms form and show the balance in a label.


πŸŽ“ Want to Go Further?

  • Use access modifiers to hide logic (private, protected, internal)
  • Explore auto-properties with private setters
  • Chain methods and properties for clean APIs (cat.Eat("fish").Purr())
  • Learn about inheritance and override methods later in the course

πŸ’¬ Want help designing your class logic for a real app idea (e.g., quiz engine, product form, game logic)?
Send us your concept β€” We’ll help you structure the class with proper encapsulation or join our OOP C# Course