Home » C# programming

Constructor overloading of structure in C#

In this article, we will learn about constructor overloading in C#, what are the base on which constructor overloading performs etc.
Submitted by IncludeHelp, on January 16, 2018

Prerequisite: Constructors in C#

When more than one constructor are defined in the same program is known as constructor overloading. In C# we can overload constructor on this basis of:

  1. Type of argument
  2. Number of argument
  3. Order of argument

In the given example, we have two parameterized constructors (as we know that constructor names are same as the class name), which have different type of arguments.

First constructor has following declaration:

public Student( int x, string s)

and, second has:

public Student(string s, int x)

Both declarations have different type of parameters, so the constructor overloading is possible without any 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(101,"Shaurya Pratap Singh");
            Student S2 = new Student("Pandit Ram Sharma",102);

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

Output

Roll Number: 101
Name: Shaurya Pratap Singh
Roll Number: 102
Name: Pandit Ram Sharma 





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.