Lesson 11 of 15

Classes

Classes

A class is a blueprint for objects. It bundles data (fields) and behavior (methods):

class Dog {
    public string Name;
    public int Age;

    public Dog(string name, int age) {
        Name = name;
        Age = age;
    }

    public string Describe() => $"{Name} is {Age} years old.";
}

var dog = new Dog("Rex", 3);
Console.WriteLine(dog.Describe()); // Rex is 3 years old.
Console.WriteLine(dog.Name);       // Rex

Constructor

The constructor runs when you create an object with new. It initializes the object's state.

Access Modifiers

  • public — accessible from anywhere
  • private — only accessible within the class (default)
  • protected — accessible within the class and subclasses

Your Task

Create a Rectangle class with:

  • double Width and double Height fields
  • A constructor taking width and height
  • A double Area() method that returns width × height
  • A double Perimeter() method that returns 2 × (width + height)
WasmSharp (.NET) loading...
Loading...
Click "Run" to execute your code.