CodeGym /Courses /C# SELF /Creating Objects with the new Operator

Creating Objects with the new Operator

C# SELF
Level 16 , Lesson 2
Available

1. How to Properly Create an Object

The new operator in C# is like a magic button that turns a schematic "blueprint" (our class) into a real instance (object) you can actually work with. To put it simply: a class defines what the object can do and what properties it has, and new creates that object in your computer's memory.

Without the new operator, our classes would be like blueprints without any buildings: you can admire them, talk about them, but you can't jump on them or spill tea on an alcantara chair.

If a class is a pizza recipe, then the new operator is the chef who uses that recipe to make a real, tasty pizza. The object is the result: a pizza in a box, ready to eat.

Syntax

Let's see how to use this all-powerful new. Here's the basic syntax if we have a Contact class:

Contact cont = new Contact();
Creating an object with new
  • Contact on the left — that's the type of variable we're creating.
  • cont — the variable name (pick meaningful ones if you don't want to suffer during debugging later).
  • new Contact() — calling the new operator, which creates an object of type Contact.

In Memory

When this code runs, the operating system reserves a chunk of memory for the new object and returns a reference (address) where this object "lives." This reference is stored in the cont variable.

Diagram

+------------------+             +--------------------+
|  variable cont   | --------->  |   Contact Object   |
+------------------+             +--------------------+
          |
          |       (contains name, phone, email, ...)
          |
         address

2. Creating Contact Objects

In previous examples, we came up with this class:

public class Contact
{
    public string Name;
    public string Phone;
    public string Email;
}

Now let's create a new object of type Contact:


Contact friend = new Contact();
friend.Name = "Ivan Ivanov";
friend.Phone = "+1-999-123-45-67";
friend.Email = "ivan@example.com";

Console.WriteLine($"Name: {friend.Name}, Phone: {friend.Phone}, Email: {friend.Email}");

What's happening here:

  1. We create an object using new Contact().
  2. We assign values to its fields.
  3. We print the data to the screen.

Example 2:

Let's add working with multiple contacts — we'll create another object:

Contact boss = new Contact();
boss.Name = "Anastasiya Sergeevna";
boss.Phone = "+1-888-765-43-21";
boss.Email = "nastya@company.com";

Console.WriteLine($"Boss: {boss.Name}, Phone: {boss.Phone}");

Doesn't it feel like filling out a form for each friend? That's exactly how objects work: each created instance gets its own unique values and stores them separately from the others!

3. Using an Array of Objects

If we need to store not one or two, but say, ten contacts, it makes sense to keep them in an array:


Contact[] contacts = new Contact[3];           // array for 3 objects

contacts[0] = new Contact();
contacts[0].Name = "Denis";
contacts[0].Phone = "+7-911-111-22-33";

contacts[1] = new Contact();
contacts[1].Name = "Maria";
contacts[1].Phone = "+7-915-123-45-67";

contacts[2] = new Contact();
contacts[2].Name = "Petr";
contacts[2].Phone = "+7-921-543-21-00";

// Print them all to the screen
for (int i = 0; i < contacts.Length; i++)
{
    Console.WriteLine($"Contact {i+1}: {contacts[i].Name}, {contacts[i].Phone}");
}

Important: we use new for each element of the array! Just creating the array doesn't create the objects themselves, it only prepares space for references to them.

4. The new Operator and Default Value

Sometimes people ask — what if I just declare a variable of type Contact but don't assign it an object with new? What happens?


Contact someContact;
someContact.Name = "Error";    // Compilation error!

But if you write:

Contact someContact = null;

then if you try to access someContact.Name your program will "crash" with the infamous exception:

System.NullReferenceException: Object reference not set to an instance of an object.

To avoid this, always initialize objects with new before using them.

5. Calling the Constructor

When you write new Contact(), at that moment a special method is called — the constructor. Right now, our class doesn't explicitly have any constructors, so the implicit (default) constructor is called, which creates the object and fills all fields with default values (null for reference types and zero for numbers).

In the next lecture, you'll learn how to create your own constructors — for example, to immediately pass in a name and phone. For now, we only have the parameterless constructor.

Real Life Examples

Working with objects via the new operator is the daily grind for any C# developer. Imagine:

  • You create a user on a website — in code, a new User object appears.
  • You open an order in an online store — a new Order pops up.
  • You enter book data — a new Book object.

In any modern C# program, you'll see thousands of lines with the new operator.

Memory Before Creating an Object


            Contact firstContact; // Variable, but points to nothing
+--------------------------+
|   firstContact           |---->  null (nothing!)
+--------------------------+

After Creating the Object


Contact firstContact = new Contact();
+--------------------------+                 +----------------------+
|   firstContact           |---------------->|   Contact Object     |
+--------------------------+                 +----------------------+

6. Practical Example

Let's say we want to let the user create new contacts by typing them in:


Console.WriteLine("Enter name:");
string name = Console.ReadLine();

Console.WriteLine("Enter phone:");
string phone = Console.ReadLine();

Contact newContact = new Contact();
newContact.Name = name;
newContact.Phone = phone;

Console.WriteLine($"Saved contact: {newContact.Name}, {newContact.Phone}");

Now every user input will create its own unique object in memory, which you can store, change, print — do whatever you want with it!

7. Typical Mistakes and Funny Pitfalls

Mistake #1: forgot to call new before working with the object.
If you declare a variable but don't initialize it, you're risking either a compilation error or a NullReferenceException at runtime. Classic: if you declare an object — immediately create it with new if you actually need it.

Mistake #2: created an array of objects, but didn't create the objects themselves.
Here's a common trap: you create an array of type Contact[], but forget that inside it's just a bunch of nulls. Trying to access contacts[0].Name will crash. You need to initialize each element of the array separately: contacts[i] = new Contact();.

Mistake #3: confused a method with a property.
Sometimes beginners think you can use a method like a field: they write student.GetName instead of student.GetName(). This will work if you don't try to use the result right away — but the compiler will complain if you try to use the "method" where a value is expected. Always check: a method should be called with parentheses, even if it takes no parameters.

2
Task
C# SELF, level 16, lesson 2
Locked
A simple class using the new operator
A simple class using the new operator
2
Task
C# SELF, level 16, lesson 2
Locked
Creating an Array of Objects
Creating an Array of Objects
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION