What is new operator in C# and how to use new operator

Description

We use new operator to create a new instance from a type.

Syntax

The new operator has this general form:

class-var = new class-name();
  • class-var is a variable of the class type being created.
  • class-name is the name of the class that is being instantiated.

The class name followed by parentheses specifies the constructor for the class.

new with value object

Use new operator with value objects


using System; /*  w  w  w  .  j a v  a 2 s.c  o  m*/
 
class MainClass {  
  public static void Main() {  
    int i = new int(); // initialize i to zero 
 
    Console.WriteLine("The value of i is: " + i); 
  }  
}

The code above generates the following result.

Creating Objects

A class defines a type of object, but it is not an object itself. An object is an instance of a class.

Objects can be created by using the new keyword followed by the name of the class.


Rectangle object1 = new Rectangle();

object1 is a reference to an object based on Rectangle. object1 refers to the new object but does not contain the object data itself.

In fact, you can create an object reference without creating an object at all:

Rectangle object2;

A reference can be made to refer to an object, either by creating a new object, or by assigning it to an existing object, such as this:


Rectangle object3 = new Rectangle();
Rectangle object4 = object3;

The code above creates two object references that both refer to the same object. Therefore, any changes to the object made through object3 will be reflected in subsequent uses of object4.

Because objects that are based on classes are referred to by reference, classes are known as reference types.





















Home »
  C# Tutorial »
    Custom Types »




C# Class
C# Struct
C# Interface
C# Inheritance
C# Namespace
C# Object
C# Delegate
C# Lambda
C# Event
C# Enum
C# Attribute
C# Generics
C# Preprocessor