I'm going to show VB.NET code first because the behavior of its C# equivalent is more confusing (see below).
Consider the following three classes:
Public Class BaseClass
Private Shared Rand As New Random
Public Shared Function CreateDerived() As BaseClass
Return If(Rand.Next(1, 3) = 1, New DerivedClass1(), New DerivedClass2())
End Function
End Class
Public Class DerivedClass1
Inherits BaseClass
Sub New()
MyProperty = 1
End Sub
Friend Property MyProperty As Integer
End Class
Public Class DerivedClass2
Inherits BaseClass
Sub New()
MyProperty = 2
End Sub
Friend Property MyProperty As Integer
End Class
Now, when I try to do something like this:
Sub Foo()
Dim targetClass As BaseClass = BaseClass.CreateDerived()
Dim Casted
If TypeOf (targetClass) Is DerivedClass1 Then
Casted = DirectCast(targetClass, DerivedClass1)
ElseIf TypeOf (targetClass) Is DerivedClass2 Then
Casted = DirectCast(targetClass, DerivedClass2)
Else
Exit Sub
End If
Console.WriteLine(Casted.MyProperty) 'Throws an exception.
End Sub
I don't seem to be able to access MyProperty
, and I receive the following exception:
Public member 'MyProperty' on type 'DerivedClass1' not found.
So, when I change the access level of MyProperty
to Public
, the code works as expected.
The weird part is when I try the C# equivalent of the above code on VS 2015, it works just fine, But on .NET Fiddler, it doesn't.
Here's the C# example on .NET Fiddler where I get the same behavior as VB.NET.
So, is there something I'm doing wrong?