Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to instantiate a class in C#?
In C#, you create an instance of a class using the new operator. This process is called instantiation, which allocates memory for the object and calls the class constructor.
Syntax
Following is the basic syntax for instantiating a class −
ClassName objectName = new ClassName();
For classes with parameterized constructors −
ClassName objectName = new ClassName(parameters);
Using Default Constructor
When you instantiate a class without parameters, it calls the default constructor. Here's an example using a Line class −
using System;
class Line {
private double length;
public Line() {
Console.WriteLine("Object is being created");
}
public void setLength(double len) {
length = len;
}
public double getLength() {
return length;
}
static void Main(string[] args) {
Line line = new Line();
line.setLength(6.0);
Console.WriteLine("Length of line: {0}", line.getLength());
}
}
The output of the above code is −
Object is being created Length of line: 6
Using Parameterized Constructor
You can also instantiate a class by passing values to a parameterized constructor −
using System;
class Student {
private string name;
private int age;
public Student(string studentName, int studentAge) {
name = studentName;
age = studentAge;
Console.WriteLine("Student object created");
}
public void DisplayInfo() {
Console.WriteLine("Name: {0}, Age: {1}", name, age);
}
static void Main(string[] args) {
Student student1 = new Student("Alice", 20);
Student student2 = new Student("Bob", 22);
student1.DisplayInfo();
student2.DisplayInfo();
}
}
The output of the above code is −
Student object created Student object created Name: Alice, Age: 20 Name: Bob, Age: 22
Multiple Object Instantiation
You can create multiple objects of the same class, each having its own set of instance variables −
using System;
class Rectangle {
private double width, height;
public Rectangle(double w, double h) {
width = w;
height = h;
}
public double GetArea() {
return width * height;
}
static void Main(string[] args) {
Rectangle rect1 = new Rectangle(5.0, 10.0);
Rectangle rect2 = new Rectangle(3.0, 7.0);
Rectangle rect3 = new Rectangle(2.5, 4.0);
Console.WriteLine("Rectangle 1 Area: " + rect1.GetArea());
Console.WriteLine("Rectangle 2 Area: " + rect2.GetArea());
Console.WriteLine("Rectangle 3 Area: " + rect3.GetArea());
}
}
The output of the above code is −
Rectangle 1 Area: 50 Rectangle 2 Area: 21 Rectangle 3 Area: 10
Conclusion
Class instantiation in C# uses the new operator to create objects and call constructors. You can instantiate classes with default constructors, parameterized constructors, or create multiple objects of the same class, each maintaining its own state and behavior.
