Perfect Understanding of new() in C#

Perfect Understanding of new() in C#

Using new() in C# seems simple. You add new, and suddenly an object appears in memory, ready to use. But under the hood, this single line of code performs two distinct operations.

First, it allocates memory. Second, it initializes the object by calling its constructor. These two actions often happen together, so we tend to see them as one. But conceptually, they are entirely different responsibilities.

new Only Allocates Memory

The new keyword itself is responsible for memory allocation only.

  • For structs, memory is allocated on the stack.
  • For classes, memory is allocated on the heap.

This means new simply tells the runtime to "reserve space"—it doesn't say what to put in that space. That job belongs to something else.

Initialization Happens via ()

The parentheses () represent a call to a constructor function, just like when calling any other method in C#.

This constructor sets default values:

  • Numeric fields become 0
  • bool fields become false
  • Reference types like string become null

Since C# forbids the use of uninitialized variables, using new() ensures that the object is safe to use immediately after it's declared.

struct MyStruct
{
    public int number;
    public string text;
}

MyStruct a;

// Error: Use of unassigned local variable 'a'
Console.WriteLine(a.number);

// Correct: Initialized via constructor
MyStruct b = new MyStruct();
Console.WriteLine(b.number); // Outputs: 0
Console.WriteLine(b.text);   // Outputs: null

Struct vs Class : Different Memory, Same Logic

  • new MyStruct() → stack allocation + constructor call
  • new MyClass() → heap allocation + constructor call

So even though they are stored differently in memory, the logic is the same: new allocates, and () initializes.

Summary

  • new() performs two steps: memory allocation and constructor call.
  • Both structs and classes use a default constructor to initialize their fields to 0, false, or null.
  • Classes must be created using new() to be usable.
  • Structs can be declared without new, but their fields must be manually initialized before use.

Popular posts from this blog

Understanding Arrays as Reference Types in C#

Setting Up a Basic Follow Camera with Cinemachine 3.x

Understanding and Using ? (nullable) in C#