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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.