0
0
CsharpHow-ToBeginner · 4 min read

How to Create Object in C#: Syntax and Examples

In C#, you create an object by using the new keyword followed by the class name and parentheses, like new ClassName(). This allocates memory and calls the class constructor to initialize the object.
📐

Syntax

To create an object in C#, use the new keyword followed by the class name and parentheses. This calls the constructor to set up the object.

  • new: keyword to create a new object
  • ClassName(): calls the constructor of the class
  • variable: stores the reference to the created object
csharp
ClassName variable = new ClassName();
💻

Example

This example shows how to create an object of a simple Car class and access its properties.

csharp
using System;

class Car
{
    public string Make;
    public string Model;

    public Car(string make, string model)
    {
        Make = make;
        Model = model;
    }

    public void DisplayInfo()
    {
        Console.WriteLine($"Car make: {Make}, model: {Model}");
    }
}

class Program
{
    static void Main()
    {
        Car myCar = new Car("Toyota", "Corolla");
        myCar.DisplayInfo();
    }
}
Output
Car make: Toyota, model: Corolla
⚠️

Common Pitfalls

Common mistakes when creating objects in C# include:

  • Forgetting to use the new keyword, which means no object is created and the variable is uninitialized.
  • Not matching the constructor parameters when calling new ClassName().
  • Trying to use an object before it is created.

Always ensure the constructor parameters match and the object is initialized before use.

csharp
/* Wrong: missing new keyword */
Car car1;
// car1.DisplayInfo(); // This will cause an error because car1 is uninitialized

/* Right: using new keyword and constructor */
Car car2 = new Car("Honda", "Civic");
car2.DisplayInfo();
Output
Car make: Honda, model: Civic
📊

Quick Reference

StepDescriptionExample
1Declare a variable of the class typeCar myCar;
2Create a new object with new and constructormyCar = new Car("Ford", "Focus");
3Use the object via its variablemyCar.DisplayInfo();

Key Takeaways

Use the new keyword followed by the class constructor to create an object.
Always match constructor parameters when creating an object.
Do not use an object before it is created with new.
Store the created object in a variable to access it later.
Creating an object allocates memory and initializes it via the constructor.