Default constructors in C#

Realize: What is a default constructor in C#? How it is pronounced and characterized, what default constructor does?

A default constructor is otherwise called zero contention or no contention constructors. It is utilized to introduce information individuals from the class.

It doesn’t have any contention. Note that – If we don’t make constructor in client characterized class. At that point compiler consequently embeds a constructor with the void body in gathered code.

We can likewise characterize constructor outside the class. It doesn’t have any arrival type.

Think about the example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1

	//class definition
	class Student
		//private data members 
		private int     rollno  ;
		private string  name    ;
		private int     age     ;

		//default constructor 
		public Student()
			//initializing data members with default values
			rollno  = 121       ;
			name    = "Kishan"   ;
			age     = 16;

		//method to set values 
		public void setInfo(string name, int rollno, int age) 
			this.rollno = rollno  ;
			this.age  = age; = name;

		//method to display values
		public void printInfo()
			Console.WriteLine("Student Record: ");
			Console.WriteLine("\tName     : " + name  );
			Console.WriteLine("\tRollNo   : " + rollno);
			Console.WriteLine("\tAge      : " + age   );


	//main class, in which we are writing main method
	class Program
		//main method
		static void Main()
			//creating object of student class
			Student S1 = new Student();
			//printing the values, initialized through 
			//default constructor 

			//creating another object 
			Student S2 = new Student();
			//providing values 
			S2.setInfo("Durgesh", 114, 19);
			//printing the values, defined by the setInfo() method


Student Record:
        Name     : Kishan
        RollNo   : 121
        Age      : 12
Student Record:
        Name     : Durgesh
        RollNo   : 114
        Age      : 19

Here, individuals from object S1 will be instated through default constructor, the default values are:

Leave a Comment

error: Alert: Content is protected!!