Can you call a constructor from another constructor of the Class in .NET?

Yes. You can call a constructor from another constructor using this keyword.



Consider the following example:

class sampleClass {
int member1;
string member2;
public sampleClass(int data) {
member1 = data;
}
public sampleClass(int data, string strValue) : this(data) {
member2 = strValue;
}
public void getData() {
Console.WriteLine(“Member1: “+member1+” Member2: “+member2);
}
}
class testClass {
public static void Main() {
sampleClass obj = new sampleClass(10, “Good Day!”);
obj.getData();
}
}

Output of this code will be:

Member1:10 Member2: Good Day!

In this example, you created an instance of sampleClass by calling the two argument constructor. In the two argument constructor, you call the one argument constructor in which value for member1 is set. After executing the call, the two argument constructor assigns value to member2.

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