Home » .Net

Default constructors in C#

Learn: What is default constructor in C#? How it is declared and defined, what default constructor does?

Default constructor is also known as zero argument or no argument constructors. It is used to initialize data members of class.

It does not have any argument. Note that - If we do not create constructor in user defined class. Then compiler automatically inserts a constructor with empty body in compiled code.

We can also define constructor outside the class. It does not have any return type.

Consider 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  = 101       ;
			name    = "Herry"   ;
			age     = 12;
		}

		//method to set values 
		public void setInfo(string name, int rollno, int age) 
		{
			this.rollno = rollno  ;
			this.age  = age;
			this.name = 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 
			S1.printInfo();

			//creating another object 
			Student S2 = new Student();
			//providing values 
			S2.setInfo("Mark", 102, 13);
			//printing the values, defined by the setInfo() method
			S2.printInfo();
		}
	}
}

Output

Student Record:
        Name     : Herry
        RollNo   : 101
        Age      : 12
Student Record:
        Name     : Mark
        RollNo   : 102
        Age      : 13

Here, members of object S1 are going to be initialized through default constructor, the default values are:

Name : "Herry"
RollNo: 101
Age : 12





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.