Codeloft
0 0 XP

Classes and objects

9 min 20 XP + 10 for no hints

A class is a blueprint and an object is one thing made from it. Classes bundle data, called fields, with methods that work on that data.

Create an object with new: Book b = new Book();. Then use a dot to set data and call methods: b.Title = "Wonder";

Mark members public so other code can use them. These methods aren't static: each object has its own data, so you call them on an object.

Example
class Dog
{
    public string Name;
    public void Bark()
    {
        Console.WriteLine($"{Name} says woof!");
    }
}

// inside Main:
Dog rex = new Dog();
rex.Name = "Rex";
rex.Bark();
Output
Rex says woof!
One class can make as many objects as you like, and each one keeps its own data.

Your tasks

0 of 4 done
  1. Define class Car
  2. Give it a public string Model
  3. Add a public void Honk() that prints "Beep!"
  4. Create a Car with new and call Honk()

Quick check

Which keyword creates a new object in C#?

Program.csChecked as you type
No problems found. Unclosed tags, missing semicolons and errors show up here in plain words.