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!

Load comments ↻





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