0
0
C Sharp (C#)programming~5 mins

Object instantiation with new in C Sharp (C#)

Choose your learning style9 modes available
Introduction

We use new to create a fresh copy of a class so we can use it in our program. It helps us make real things from blueprints.

When you want to create a new person in a game with their own name and score.
When you need a new car object to keep track of its speed and color.
When you want to make a new bank account with its own balance.
When you want to create multiple objects that behave independently.
Syntax
C Sharp (C#)
ClassName variableName = new ClassName();

The new keyword tells the computer to make a new object.

You usually put parentheses () after the class name to call its constructor.

Examples
This creates a new Person object and stores it in variable p.
C Sharp (C#)
Person p = new Person();
This makes a new Car object called myCar.
C Sharp (C#)
Car myCar = new Car();
This creates a new BankAccount object named account.
C Sharp (C#)
BankAccount account = new BankAccount();
Sample Program

This program creates a new Person object named p. It sets the name and age, then prints an introduction.

C Sharp (C#)
using System;

class Person
{
    public string Name;
    public int Age;

    public Person()
    {
        Name = "Unknown";
        Age = 0;
    }

    public void Introduce()
    {
        Console.WriteLine($"Hi, my name is {Name} and I am {Age} years old.");
    }
}

class Program
{
    static void Main()
    {
        Person p = new Person();
        p.Name = "Alice";
        p.Age = 30;
        p.Introduce();
    }
}
OutputSuccess
Important Notes

Every time you use new, you get a separate object with its own data.

If you forget new, you only have a reference, not an actual object.

Summary

new creates a new object from a class blueprint.

Use it when you want to work with fresh, independent objects.

Remember to call the constructor with parentheses ().