How do you perform constructor overloading in C#?

C# permits constructors of a class to be overloaded. Here is an example demonstrating it:



class sampleClass {
public int member1,member2;
public sampleClass() {
member1 = 10;
member2 = 20;
}
public sampleClass(int member1) {
this.member1 = member1;
member2 = 200;
}
public sampleClass(int member1, int member2) {
this.member1 = member1;
this.member2 = member2;
}
public static void Main() {
sampleClass obj1 = new sampleClass();
sampleClass obj2 = new sampleClass(100);
sampleClass obj3 = new sampleClass(1000,2000);
Console.WriteLine(“obj1 members:{0},{1}”, obj1.member1, obj1.member2);
Console.WriteLine(“obj2 members:{0},{1}”, obj2.member1, obj2.member2);
Console.WriteLine(“obj3 members:{0},{1}”, obj3.member1, obj3.member2);
}
}

Output of this code will be:

obj1 members:10,20
obj2 members:100,200
obj3 members:1000,2000

In this example, the constructor of sampleClass is overloaded to accept no arguments, one argument and two arguments respectively. While creating an instance of sampleClass, appropriate constructor will be invoked based on the arguments passed.

| Can you call a constructor from another constructor of the Class in .NET? | Difference between Response.Output.Write() method and Response.Write() method in .NET | How do you establish multiple inheritance in C#? | How do you introduce a ReadOnly property in C#? | How do you perform constructor overloading in C#? | Is catch(Exception) recommended to be used in .NET? | What are the different access modifiers available in C#? | What are the different ways of overloading in C#? | What are the members of stringbuilder class in C#? | What is Multicast Delegate? Explain it with example in C# | What is the difference between abstract class and interface in .NET? | What is the difference between Clone and CopyTo methods in .NET | What is the difference between const and readonly in .NET | What is the difference between directcast and ctype in .NET? | What is the difference between out and ref parameters in .NET | What is the difference between public assembly and private assembly in .NET | What is the difference between strong typing and weak typing in .NET? | What is the difference between Trace and Debug in .NET | What is the need for Abstract Factory Pattern in C#? | What is the need for Adapter Pattern in C# |


“Amazon and the Amazon logo are trademarks of Amazon.com, Inc. or its affiliates.”

| Privacy Policy for www.dotnet-guide.com | Disclosure | Contact |

Copyright - © 2004 - 2024 - All Rights Reserved.