Overridden Properties handled differently in C# and VB

(Check here for an update to this post!)

I have a game in my mind that I keep trying to program.  I'm sure many people have done this; the game never really gets anywhere, but it's always “getting there“.  Anyway, I wrote many of the classes for this game in C#.  Later, for no really good reason, I decided to translate these classes to VB.  (Yes, I'm one of those guys.)

I discovered an interesting fact:  C# and VB handle overloaded properties differently.  Let's look at an example.

What I want to do is to make a read/write property in my base class, then override this property in a derived class.  The property in the derived class should be read-only. In C#, this works as expected.  However, in VB, this gives a compiler error that states that the base class cannot be overridden because the derived class's property differs from the base class's property by “readonly or writeonly.“  Why the difference?

In C#:
public abstract class Weapon
{
     private bool _IsLimited = false;

     public Weapon()
     {
     }

     public virtual bool Limited
     {
          get
          {
               return _IsLimited;
          }
          set 
          {
               _IsLimited = value;
          }
     }
}

public abstract class BeamWeapon: Weapon
{
     public BeamWeapon()
     {
         
base.Limited = false;
     }

     public override bool Limited
     {
          get
          {
               return base.Limited;
          }
     }
}

 

In VB:
Public MustInherit Class Weapon

     Private _IsLimited As Boolean

     Public Sub New()
     End Sub

     Public Overridable Property Limited() As Boolean
          Get
               Return _IsLimited
          End Get

          Set(ByVal Value As Boolean)
               _IsLimited = Value
          End Set
     End Property
End Class

Public MustInherit Class BeamWeapon
     Inherits Weapon

     Public Sub New()
          
MyBase.Limited = False
     End Sub

     ' This causes an error!
     Public Overrides ReadOnly Property Limited() As Boolean
          Get
               Return MyBase.Limited
          End Get
     End Property
End Class

Comments