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 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.
|