In C# I have the following code:
- a base class with a virtual InitClass() function
- a child class which overrides the InitClass() function. In this function I set a private variable
- a public property exposing my private field
namespace InheritenceTest { class Program { static void Main(string[] args) { ChildClass childClass = new ChildClass(); Console.WriteLine(childClass.SomeString); Console.ReadLine(); } }
public class BaseClass
{
public BaseClass()
{
InitClass();
}
protected virtual void InitClass()
{
// Do Nothing here
}
}
public class ChildClass: BaseClass
{
private string _someString = "Default Value";
public ChildClass()
{
}
protected override void InitClass()
{
base.InitClass();
_someString = "Set in InitClass()";
}
public string SomeString
{
get { return _someString; }
set { _someString = value; }
}
}
}
The Console output from this program is "Set in InitClass()".
Now I converted this piece of code to VB.NET.
Imports System
Imports System.Collections.Generic
Imports System.Text
Namespace InheritenceTest
Module Program
Public Sub Main(ByVal args As String())
Dim childClass As New ChildClass()
Console.WriteLine(childClass.SomeString)
Console.ReadLine()
End Sub
End Module
Public Class BaseClass
Public Sub New()
InitClass()
End Sub
Protected Overridable Sub InitClass()
' Do Nothing here
End Sub
End Class
Public Class ChildClass
Inherits BaseClass
Private _someString As String = "Default Value"
Public Sub New()
End Sub
Protected Overrides Sub InitClass()
MyBase.InitClass()
_someString = "Set in InitClass()"
End Sub
Public Property SomeString() As String
Get
Return _someString
End Get
Set(ByVal value As String)
_someString = value
End Set
End Property
End Class
End Namespace
The output of this VB.NET program is "Default Value".
When looking at the code while debugging (the VB.NET code) you see that when the constructor finished doing it's job, the default Value is set, while for C# it's the other way around (first the default value is set, than the constructor is called).
Can anyone explain me why this is the case? And which of the 2 languages is "correct"?