Recently I have been trying to learn C#. As a long-time Java developer, there have been a few surprises. C# and Java have a lot in common, so it’s hard for me to notice some of the subtle differences. Today, for instance, I found out that method overriding in C# takes extra effort. In Java, you define methods and then override them in subclasses by simply declaring a method with the same name and arguments. That is not the case in C#, but it took me a while to figure out why the Java code I was converting to C# was not working correctly.
With C#, you have to add the “virtual” keyword to any method you intend to override. In subclasses, you have to add the “override” keyword. This is illustrated below for a “makeMove” method for the game of Gomoku.
public class GomokuPlayer ... public virtual Move makeMove (State gstate, int whichPlayer) { ... return someMove; } ... }
public class FastPlayer : GomokuPlayer { ... public override Move makeMove (State gstate, int whichPlayer) { ... return myMove; } ... }
C# virtual and override are well explained here: http://www.codeproject.com/Articles/18734/Method-Overriding-in-C
it’s all about the ” virtual ” word 🙂