Constructor overloading of structure in C#

Constructor overloading of structure in C#

In this article, we will find out about constructor over-burdening in C#, what is the base on which constructor over-burdening performs and so forth.

At the point when more than one constructor is characterized in a similar program is known as constructor over-burdening. In C# we can over-burden constructor on this premise of:

  1. Kind of contention
  2. Number of contention
  3. Request of contention

In the given example, we have two parameterized constructors (as we realize that constructor names are the same as the class name), which have a distinctive sort of contentions.

The first constructor has the following assertion:

public Student( int x, string s)

furthermore, second has:

public Student(string s, int x)

The two presentations have diverse sort of parameters, so the constructor over-burdening is conceivable with no issue.

Example:

using System;
using System.Collections;

namespace ConsoleApplication1
{

    struct Student
    {
        public int roll_number;
        public string name;

        public Student( int x, string s)
        {
            roll_number = x;
            name = s;
        }

        public Student(string s, int x)
        {
            roll_number = x;
            name = s;
        }

        public void printValue()
        {
            Console.WriteLine("Roll Number: " + roll_number);
            Console.WriteLine("Name: " + name);
        }
    }
    class Program
    {
        static void Main()
        {
            Student S1 = new Student(203,"Aakash Kumar Kaushik");
            Student S2 = new Student(204,"Kishan Kumar Kaushik");

            S1.printValue();
            S2.printValue();
        }
    }
}

Output

Roll Number: 203
Name: Aakash Kumar Kaushik
Roll Number: 204
Name: Kishan Kumar Kaushik

Recent Posts

error: Alert: Content is protected!!