Skip to content

Classes and Objects

Sann Lynn Htun edited this page Nov 19, 2024 · 2 revisions

C# Classes and Objects

A class is a blueprint for creating objects, providing properties and methods to define behavior. An object is an instance of a class, encapsulating data and functionality.


Key Concepts of Classes and Objects

1. Class

A class is a user-defined reference type that acts as a blueprint for objects.

Syntax:

class ClassName {
    // Fields
    // Properties
    // Methods
    // Constructors
}

Example:

class Car {
    public string Brand; // Field
    public void Drive() { // Method
        Console.WriteLine($"{Brand} is driving.");
    }
}

2. Object

An object is an instance of a class that holds data and can invoke methods.

Syntax:

ClassName obj = new ClassName();

Example:

Car myCar = new Car();
myCar.Brand = "Toyota"; // Accessing field
myCar.Drive(); // Output: Toyota is driving.

Components of Classes

1. Fields

Variables declared within a class to hold data.

Example:

class Person {
    public string Name;
    public int Age;
}

2. Properties

Encapsulate fields with get and set for controlled access.

Example:

class Person {
    private string name;
    public string Name {
        get { return name; }
        set { name = value; }
    }
}

3. Methods

Functions inside a class that define behavior.

Example:

class Calculator {
    public int Add(int a, int b) {
        return a + b;
    }
}

4. Constructors

Special methods to initialize objects.

Example:

class Car {
    public string Brand;
    public Car(string brand) { // Constructor
        Brand = brand;
    }
}
Car myCar = new Car("Ford"); // Constructor invoked

Access Modifiers

Control access to class members.

Modifier Description Example
public Accessible from anywhere. public int Age;
private Accessible only within the same class. private int age;
protected Accessible within the same class and derived classes. protected int age;
internal Accessible within the same assembly. internal int age;

Example: Full Class Implementation

class Dog {
    // Fields
    private string breed;

    // Property
    public string Breed {
        get { return breed; }
        set { breed = value; }
    }

    // Constructor
    public Dog(string breed) {
        Breed = breed;
    }

    // Method
    public void Bark() {
        Console.WriteLine($"{Breed} is barking.");
    }
}

// Object creation
Dog myDog = new Dog("Golden Retriever");
myDog.Bark(); // Output: Golden Retriever is barking.

Summary

  • Class: Blueprint for creating objects, containing fields, properties, methods, and constructors.
  • Object: Instance of a class, encapsulating state and behavior.
  • Components: Include fields (data), properties (controlled access), methods (behavior), and constructors (initialization).
  • Access Modifiers: Control visibility and accessibility of members.

Classes and objects form the foundation of Object-Oriented Programming in C#, promoting modularity, reusability, and encapsulation.


Why Use Properties Instead of Fields?

Using properties instead of directly exposing fields in C# is a good practice due to the benefits of encapsulation, data validation, and flexibility. While fields are simple and straightforward, they lack the ability to control how data is accessed or modified.

1. Encapsulation and Control

  • Fields: Directly exposing fields makes it impossible to control how data is accessed or modified.
  • Properties: With get and set, you can control the logic for accessing or modifying a value.

Example:

class Person {
    public string Name; // Direct field (no control)
}

Versus:

class Person {
    private string name;
    public string Name {
        get { return name; }
        set {
            if (!string.IsNullOrEmpty(value)) { // Validation
                name = value;
            } else {
                throw new ArgumentException("Name cannot be empty.");
            }
        }
    }
}

2. Data Validation

  • Fields: No way to validate data before setting it.
  • Properties: You can add logic to ensure data consistency.

Example:

class Employee {
    private int age;
    public int Age {
        get { return age; }
        set {
            if (value > 0) {
                age = value; // Only set valid ages
            } else {
                throw new ArgumentException("Age must be positive.");
            }
        }
    }
}

3. Read-Only or Write-Only Access

  • Fields: Cannot restrict access for reading or writing.
  • Properties: Can make a property read-only (get only) or write-only (set only).

Example:

class Product {
    private int stock;
    public int Stock {
        get { return stock; } // Read-only
    }

    public void Restock(int amount) { // Write logic encapsulated in a method
        if (amount > 0) {
            stock += amount;
        }
    }
}

4. Automatic Properties

  • Simplify property declarations while still maintaining encapsulation.

Example:

class Book {
    public string Title { get; set; } // Auto-implemented property
    public string Author { get; set; }
}

This avoids the verbosity of manually implementing backing fields unless you need custom logic.


5. Future Flexibility

  • Fields: Once exposed, you cannot later add logic to control access without breaking the API.
  • Properties: Let you modify the internal logic (e.g., add validation, logging, or computed values) without changing the external interface.

Example:

class Rectangle {
    private int length;
    public int Length {
        get { return length; }
        set { 
            if (value > 0) length = value;
        }
    }

    // Adding a computed property later
    public int Area {
        get { return length * length; } // Derived value
    }
}

When Should You Use Fields?

  • Fields are suitable for private members that are not meant to be accessed directly outside the class.
  • Use fields for constants (const) or read-only values (readonly) where properties would add unnecessary overhead.

Example:

class Circle {
    private const double Pi = 3.14159; // Constant field
    private readonly double radius;   // Read-only field

    public Circle(double radius) {
        this.radius = radius;
    }
}

Summary

Feature Field Property
Encapsulation No control over access/modification. Allows full control via get and set.
Data Validation Not possible. Can validate data before setting it.
Access Control Always read-write. Can be read-only or write-only.
Flexibility No room for future changes. Logic can evolve without breaking the interface.
Use Case Internal/private constants. Exposed data requiring control or validation.

In summary, use properties when exposing data to maintain control and flexibility. Fields are best kept private or used for fixed, internal values.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally