C# Constructor1 min read

In C#, a constructor is the member of the class and is automatically invoked once the object of the class is created. It is like a method in a program and is used for the initialization of the data members of a newly created object.

Two types of C# constructors

  1. Default constructor
  2. Parameterized constructor

Default Constructor in C#

A constructor without any parameters is called a default constructor and is invoked at the time of creating the object of the class.

Example: Default C# Constructor

Output:

Constructor Called
Constructor Called

As you can see, that the constructor is called every time we create a new object of the class. And since it is a default constructor, it has no parameter.


Parameterized Constructor in C#

A Constructor having a specific number of parameters is called Parameterized Constructor. Passing parameters is useful when you want to assign a different initial value to distinct objects.

Example: Parameterized C# Constructor

Output:

1101 Shaun 80.5
1102 Garen 90

As you can see the student details are initialized and displayed for every object created for the Student class in a program.


MORE

Java Program to find the sum of the Largest Forward Diagonal

in this tutorial, we will write a java program to find the sum of the Largest Forward Diagonal in an Arraylist (matrix). Java Program to …

C Program to search an element in an array using Pointers

A separate function( search_function()) will be created where the array pointer will be declared and the searched element along with the size of an array …

C Program to find the sum of the digits of a number using recursion function

This C program calculates the sum of digits of a given number using recursion. Here’s a concise explanation: Function Definition: sumDigits(int n) This function calculates …

C program to find factorial of a number using Ternary operator with Recursion

Recursion refers to the function calling itself directly or in a cycle. Before we begin, you should have the knowledge of following in C Programming: …

C Program to Add Two Numbers Using Call by Reference

The program takes the two numbers from the user and passes the reference to the function where the sum is calculated. You may go through …

Find the output ab, cd, ef, g for the input a,b,c,d,e,f,g in Javascript and Python

In this tutorial, we will write a program to find a pairs of elements from an array such that for the input [a,b,c,d,e,f,g] we will …