Constructor Overloading in C#


When more than one constructor with the same name is defined in the same class, they are called overloaded, if the parameters are different for each constructor.

Let us see an example to learn how to work with Constructor Overloading in C#.

In the example, we have two subjects and a string declaration for Student Name.

private double SubjectOne;
private double SubjectTwo;
string StudentName;

We are showing result of three students in different subjects. For our example, to show constructor overloading, the name is only displayed for student 3rd.

Student s1 = new Student();
Student s2 = new Student(90);
Student s3 = new Student("Amit",88, 60);

You can try to run the following code to implement constructor overloading in C#.

Example

 Live Demo

using System;
namespace Program {
   class Student {
      private double SubjectOne;
      private double SubjectTwo;
      string StudentName;
      public Student() {
         this.SubjectOne = 80;
      }
      public Student(double SubjectOne) {
         this.SubjectOne = SubjectOne;
      }
      public Student(string StudentName, double SubjectOne, double SubjectTwo) {
         this.SubjectOne = SubjectOne;
         this.SubjectTwo = SubjectTwo;
         this.StudentName = StudentName;
      }
      public double GetSubjectOneMarks() {
         return this.SubjectOne;
      }
      public double GetSubjectTwoMarks() {
         return this.SubjectTwo;
      }
      public string GetStudentName() {
         return this.StudentName;
      }
   }
   class Program {
      static void Main(string[] args) {
         Student s1 = new Student();
         Student s2 = new Student(90);
         Student s3 = new Student("Amit",88, 60);
         Console.WriteLine("One");
         Console.WriteLine("Subject One Marks: {0}", s1.GetSubjectOneMarks());
         Console.WriteLine();
         Console.WriteLine("Second");
         Console.WriteLine("Subject One Marks: {0}", s2.GetSubjectOneMarks());
         Console.WriteLine();
         Console.WriteLine("Third");
         Console.WriteLine("Student name: {0}", s3.GetStudentName());
         Console.WriteLine("Subject One Marks: {0}", s3.GetSubjectOneMarks());
         Console.WriteLine("Subject Two Marks: {0}", s3.GetSubjectTwoMarks());
         Console.ReadKey();
      }
   }
}

Output

One
Subject One Marks: 80

Second
Subject One Marks: 90

Third
Student name: Amit
Subject One Marks: 88
Subject Two Marks: 60

Updated on: 23-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements