OOP — Classes, Objects & Constructors

লেসন ৫ / ৫০

Class ও Object

public class Person {
    // Field (private)
    private int _age;

    // Property (public, modern)
    public string Name { get; set; }
    public int Age {
        get => _age;
        set {
            if (value < 0) throw new ArgumentException("Invalid age");
            _age = value;
        }
    }

    // Auto-property with default
    public string Country { get; set; } = "Bangladesh";

    // Read-only property
    public DateTime CreatedAt { get; } = DateTime.Now;

    // Constructor
    public Person(string name, int age) {
        Name = name;
        Age = age;
    }

    // Default constructor
    public Person() : this("Unknown", 0) { }    // chain

    // Method
    public void Introduce() {
        Console.WriteLine($"আমি {Name}, বয়স {Age}");
    }
}

// ব্যবহার
var p = new Person("Rahim", 25);
p.Introduce();

Object Initializer

var p = new Person {
    Name = "Karim",
    Age = 30,
    Country = "Bangladesh"
};

Access Modifiers

  • public — সবখানে
  • private — শুধু class ভিতরে
  • protected — class + derived class
  • internal — একই assembly
  • protected internal — দুটোর OR
  • private protected — দুটোর AND

this Keyword

public class Box {
    private int width;
    public Box(int width) {
        this.width = width;     // shadow সমস্যা সমাধান
    }
}

Static Class

public static class MathHelper {
    public static double PI = 3.14159;
    public static int Square(int x) => x * x;
}
// instantiate করা যায় না, শুধু MathHelper.Square(5)

Record (C# 9+) — Immutable Data Class

public record Point(double X, double Y);
var p1 = new Point(1.0, 2.0);
var p2 = p1 with { X = 5.0 };       // immutable copy
Console.WriteLine(p1 == new Point(1.0, 2.0));  // true (value equality)