I wrote a program that allow two classes to "fight". For whatever reason C# always wins. What's wrong with VB.NET ?
static void Main(string[] args) { Player a = new A(); Player b = new B(); if (a.Power > b.Power) Console.WriteLine("C# won"); else if (a.Power < b.Power) Console.WriteLine("VB won"); else Console.WriteLine("Tie"); }
Here are the players: Player A in C#:
public class A : Player { private int desiredPower = 100; public override int GetPower { get { return desiredPower; } } }
Player B in VB.NET:
Public Class B Inherits Player Dim desiredPower As Integer = 100 Public Overrides ReadOnly Property GetPower() As Integer Get Return desiredPower End Get End Property End Class
And here is a base class.
public abstract class Player { public int Power { get; private set; } public abstract int GetPower { get; } protected Player() { Power = GetPower; } }
The issue here is that VB is calling the base constructor before setting its field value. So the base Player class stores zero.
.method public specialname rtspecialname instance void .ctor() cil managed { // Code size 15 (0xf) .maxstack 8 IL_0000: ldarg.0 IL_0001: call instance void [base]Player::.ctor() IL_0006: ldarg.0 IL_0007: ldc.i4.s 100 IL_0009: stfld int32 B::desiredPower IL_000e: ret } // end of method B::.ctor
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With