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 anywhereprivate— only accessible within the class (default)protected— accessible within the class and subclasses
Your Task
Create a Rectangle class with:
double Widthanddouble Heightfields- A constructor taking
widthandheight - 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.