Classes and objects
A class is a blueprint, and a blueprint isn't a dog. To get something you can work with, you create an object, also called an instance of the class. One class can produce as many objects as you like, and each is a separate thing in memory.
The new keyword
You create an object with new, the class name and a pair of parentheses:
Dog rex = new Dog();
This one line does three jobs:
new Dog()creates a freshDogobject and runs the class's constructor, the special method that sets up a new object. If you haven't written a constructor, C# supplies an empty one with no parameters.Dog rexdeclares a variable namedrexwhose type isDog.- The
=stores a reference to the new object in that variable.
The word reference matters. For a class, the variable doesn't contain the object itself; it holds a reference that points to the object. Classes are reference types in C#.
Many objects from one class
Every call to new builds a new, independent object:
Dog rex = new Dog();
Dog buddy = new Dog();
Dog luna = new Dog();
These are three different Dog objects. They share the same blueprint, but changing one doesn't affect the others. Once the class has fields, each object will hold its own values.
Because variables hold references, copying a variable doesn't copy the object:
Dog a = new Dog();
Dog b = new Dog();
Dog c = a;
Console.WriteLine(a == b); // False: two different objects
Console.WriteLine(a == c); // True: both variables refer to the same object
For a plain class like this one, == asks whether two references point at the same object. It doesn't compare what is inside the objects. Writing c = a gives you a second name for the object, not a second dog. Only new makes another dog.
Variable type and object type
In Dog rex = new Dog(); the type name appears twice. The first Dog is the type of the variable. The second, after new, is the class being instantiated. When they are the same, C# lets you avoid the repetition in two ways:
var rex = new Dog(); // the compiler infers that rex is a Dog
Dog buddy = new(); // target-typed new: the type comes from the variable
Both lines mean exactly what Dog rex = new Dog(); means. The variable keeps a fixed type for its whole life; var only saves typing.
The null reference
A variable of a class type can also hold no object at all. That is the value null:
Dog stray = null;
Console.WriteLine(stray != null); // False
Comparing with null is how code checks whether a variable refers to an object. If you try to use a member of a null reference, such as stray.name, the program throws a NullReferenceException. A variable you have declared but never assigned is different: C# refuses to compile a program that reads a local variable before giving it a value.
Common mistakes
- Declaring without creating.
Dog rex;creates a variable, not a dog. Readingrexbefore assigning it is a compile error. - Forgetting the parentheses.
new Dogis incomplete; writenew Dog(). - Using the same variable for several dogs. If you assign
new Dog()torextwice, the first object is lost, unless another variable refers to it. - Thinking assignment copies.
Dog c = a;doesn't clone the dog. - Wrong case.
new dog()is an error, because the class is calledDog. - Writing
newwith arguments for a class that has no matching constructor.new Dog("Rex")works only after the class defines a constructor that takes a string. Constructors are the next topic.
The exercise, step by step
The Dog class is already defined. The code in MainFunction prints a line for each variable that is not null, but the variables rex, buddy and luna don't exist yet. You have to declare and fill them.
- Create the first dog. At the top of
MainFunction, writeDog rex = new Dog();. - Create the second dog on the next line:
Dog buddy = new Dog();. It is a new object, independent ofrex. - Create the third dog:
Dog luna = new Dog();.
class Dog {
}
class Solution {
public void MainFunction() {
Dog rex = new Dog();
Dog buddy = new Dog();
Dog luna = new Dog();
if (rex != null) Console.WriteLine("rex exists");
if (buddy != null) Console.WriteLine("buddy exists");
if (luna != null) Console.WriteLine("luna exists");
}
}
Each variable now refers to an object, so none of the three comparisons with null is false, and the method prints:
rex exists
buddy exists
luna exists
Key takeaways
- An object is an instance of a class, created with
new ClassName(). - Each
newmakes a separate, independent object. - A class-typed variable holds a reference; assigning one variable to another copies the reference, not the object.
varandnew()reduce repetition without changing the type.- A reference can be
null, meaning it points to no object.