Start learning free

LESSON 284 OF 674 · FUNCTIONS & CLASSES

Creating Objects in C#

Lesson

TL ; DR:

  • An object is an instance of a class — a real, usable copy made from the blueprint.


  • You create one with the new keyword:

    Dog rex = new Dog();
    

  • Each call to new creates a separate object, even if they all come from the same class.



Full lesson:

In the previous lesson you defined the Dog class — the blueprint. But a blueprint isn't a dog. To get an actual dog you can interact with, you need to create an instance of the class. An instance is also called an object.


The new keyword

To create a new object in C#, use the new keyword followed by the class name and parentheses:

Dog rex = new Dog();

What this line does:

  • new Dog() creates a fresh Dog object in memory.

  • Dog rex declares a variable named rex that holds a reference to that object.

  • The = connects the two — rex now refers to the freshly-created dog.


Many objects from one class

You can call new Dog() as many times as you want, and each call gives you a brand-new, independent object:

Dog rex   = new Dog();
Dog buddy = new Dog();
Dog luna  = new Dog();

rex, buddy, and luna are all Dog objects, but they're different objects. Changing one won't affect the others — they share the blueprint but live their own lives. (We'll start storing per-object data in the next lesson on fields.)


Variable type vs. object type

In Dog rex = new Dog(); the type appears twice for a reason:

  • The first Dog is the declared type of the variable — what kind of reference rex can hold.

  • The second Dog (after new) is the actual class being instantiated.

In simple cases like this they match. C# also lets you use var to skip the redundancy:

var rex = new Dog();   // C# infers the variable type as Dog

Your task

The Dog class is already defined for you. Inside MainFunction, create three separate Dog objects named rex, buddy, and luna. The pre-filled code below them prints a line for each object that exists, so the program should print:

rex exists
buddy exists
luna exists
STEP 1 OF 3
    Ctrl + Enter to check