Monday, May 12, 2008

C# Have a constructor call a constructor - constructor overloading

If you are a beginner C# programmer; especially coming from the VB/VB.net world, this could throw you if you do not know how. In VB, you can call a constructor from within another constructor by using me.New(arguments) statement.

In C#, you add the :this(arguments) to the constructor, and leave its body blank.

So:


public class ReportGenerator
(
public ReportGenerator(String A, String B, String C)
{
// actual constructor code goes here
}
// overloaded constructor, only two arguments
// String C can be passed as String.Empty, or a default Value "value"
public ReportGenerator(String A, String B)
:this(A, B, YourDefaultValueForStringC)
{
}
// another overloaded constructor, only one argument
// Send one additional default argument, to the constructor above.
public ReportGenerator(String A)
:this(A, YourDefaultValueForStringB)
{
}

}

No comments: