Tutorialspoint.dev

Different ways to create an Object in C#

A fully object-oriented language means everything is represented as an object but can’t differentiate between primitive types and objects of classes but C# is not purely object oriented since it supports many procedural programming concepts such as pointers to an extent. An object is a basic unit of Object Oriented Programming and represents the real-life entities. A typical C# program creates many objects, which as you know, interact by invoking methods. We can Create objects in C# in the following ways:

1) Using the ‘new’ operator: A class is a reference type and at the run time, any object of the reference type is assigned a null value unless it is declared using the new operator. The new operator assigns space in the memory to the object only during run time which means the allocation is dynamic.

Syntax:

// The className() is a call
// to the constructor
className ObjectName = new className();   

Note: The constructor can be a default constructor or a user-defined one.

Example:



// C# Program to show the use
// of the new Operator
using System;
  
namespace NewOperator {
  
class Rectangle {
  
    public int length, breadth;
  
    // Parameterized Constructor
    // User defined
    public Rectangle(int l, int b)
    {
        length = l;
        breadth = b;
    }
  
    // Method to Calculate Area
    // of the rectangle
    public int Area()
    {
        return length * breadth;
    }
}
  
// Driver Class
class Program {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating an object using 'new'
        // Calling the parameterized constructor
        // With parameters 10 and 12
        Rectangle rect1 = new Rectangle(10, 12);
  
        // To display are of the Rectangle
        int area = rect1.Area();
        Console.WriteLine("The area of the"+
                   " Rectangle is " + area);
    }
}
}

Output:

The area of the Rectangle is 120

2) Creating Reference to Existing Object: The reference can be declared only with the class name and reference name. The reference cannot exist independently. It has to be assigned to an already existing object of the same class. Any changes made in the reference will be saved to the object it is referring to. It is kind of like an alias.

Syntax:

className RefName;
RefName = objectName;

Example:

// C# Program to show the use
// of references
using System;
  
namespace Reference {
  
class Triangle {
  
    public int side, altitude;
    // Not defining a constructor
  
    // Method to calculate area
    // of the Triangle
    public double Area()
    {
        return (double)0.5 * side * altitude;
    }
}
  
// Driver Class
class Program {
  
    // Main Method
    static void Main(string[] args)
    {
        // Creating an object using new
        // calls the default constructor
        Triangle tri1 = new Triangle();
  
        // Only creates a reference of
        // type Triangle
        Triangle tri2;
  
        // Displaying area of tri1
        Console.WriteLine("Area of tri1 is " 
                             + tri1.Area());
  
        // Assigns the reference to tri1
        tri2 = tri1;
  
        // Making changes in tri2
        tri2.side = 5;
        tri2.altitude = 7;
  
        // Displaying area of tri1
        // Changes made in the reference tri2
        // are reflected in tri1 also
        Console.WriteLine("Area of tri1 is " 
                             + tri1.Area());
    }
}
}

Output:

Area of tri1 is 0
Area of tri1 is 17.5

3) Creating an Array of objects: If you need the multiple numbers of objects of the same class you can create an array of objects. This will require you to declare the array first and then initialize each element { object in this case }. You can use for loop for initialization.

Syntax:

className[] arrayName = new className[size];
// C# Program to illustrate how to 
// create the array of objects
using System;
  
namespace ArrayofObjects {
  
class Circle {
  
    public int radius;
  
    // Definig Constructor
    public Circle()
    {
        radius = 0;
    }
  
    // Method to set value of radius
    public void setValue(int r)
    {
        radius = r;
    }
  
    // Method to calculate the 
    // area of the Circle
    public double Area()
    {
        return (double)3.14 * radius * radius;
    }
}
  
// Driver Class
class Program {
  
    // Main Method
    static void Main(string[] args)
    {
        // To declare an array of two objects
        Circle[] circleArray = new Circle[2];
  
        // Initialize the objects
        circleArray[0] = new Circle();
        circleArray[1] = new Circle();
  
        // to set values for the radius
        circleArray[0].setValue(1);
        circleArray[1].setValue(2);
  
        // for loop to display areas
        for (int i = 0; i < circleArray.Length; i++) 
        {
            Console.Write("Area of circle with radius " + (i + 1));
            Console.Write(" is " + circleArray[i].Area() + " ");
        }
    }
}
}

Output:

Area of circle with radius 1 is 3.14
Area of circle with radius 2 is 12.56


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter