Overloaded Constructors in C# | | Recently, I've seen a few questions from VB.NET Programmers who are using C#. One problem they have is passing in Default Values in Constructors. The reason is that the behavior is fundamentally different in C# and you can't just substitute a few words like you normally can.
In VB.NET, this is how you'd typically accomplish this:
Imports System.Diagnostics
Public Class DefaultSample
Public Sub New()
Me.New("DefaultValue")
End Sub
Public Sub New(ByVal defaultValue As System.String)
Me.New(defaultValue, 1)
End Sub
Public Sub New(ByVal defaultValue1 As System.String, ByVal defaultValue2 As System.Int32)
Debug.WriteLine(defaultValue1, defaultValue2.ToString)
End Sub
End Class
|
The problem though is that you'd intuitively think that in C# you can substitute Me for this and you'd be off to the races. Not so. Fortunately, it's easy to do in C#:
using System;
using System.Data;
using System.Diagnostics;
namespace KDN.Samples.CSharp
{
/// <summary>
/// Summary description for DefaultSample.
///
public class DefaultSample
{
public DefaultSample() : this("DefaultValue"){}
public DefaultSample(System.String firstValue) : this("Defaultvalue", 2){}
public DefaultSample(System.String firstValue, System.Int32 secondValue)
{
Debug.WriteLine(firstValue, secondValue.ToString());
}
}
}
|
| That's all there is to it. | |