Notes from porting Java code to .NET
19 November 2011
Recently I needed to use a DFA/NFA (finite-state automata) implementation from a Java package in .NET. I could not find a port of this particular package and IKVMC was not an option since I preferred to depend only on the standard library (BCL). So, I decided to port the code myself.
In my case, the Java package didn't have unit tests (at least not publicly available on the website). How could I know that the results of the ported code are the same with the original code?
The solution I came up with was the following:
- Write integration tests, one for the ported code and one for the Java code.
- Both tests should have the same, deterministic, input.
- Keep porting enough code from the Java source in order to make the test pass.
- Verify that results are the same with the test in Java.
- Recursively repeat this process until all tests pass and yield correct results.
An example can be found here with integration tests for ported code and Java (through IKVMC).
During the process of porting I came across a few differences between Java and .NET and particularly:
- Multi-dimensional arrays syntax is slightly different.
- Substring method parameteres have different meaning.
- In C# we pass StartIndex, Length.
- In Java we pass StartIndex, EndIndex.
- In Java, the list and set implementations override equals, etc. The equivalent doesn't happen in .NET.
- Java LinkedList Add method appends the specified element to the end of the list. The equivalent in .NET is the AddLast method.
- Java LinkedList Remove(int) method removes the element at the specified position in the list and returns the element that was removed from the list. The equivalent in .NET exists only with the use of an extension method.
- What are major differences between C# and Java?
- Why should I bother about serialVersionUID?
- C# equivalent to Java's charAt()?
- Working with multidimensional arrays in C# similar to Java
- .NET port with Java's Map, Set, HashMap
- What is the difference between instanceof and Class.isAssignableFrom
- Why you should not implement ICloneable in C#?
Java SE 6 Documentation