Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

identifying code that compiles in both Java and C# but runs differently

Tags:

java

c#

I am having to port code from Java to C# (and soon the other way round) by copying and pasting and then editing compiler errors. (Please accept that this is necessary; I can explain if required). Are there cases where the same code fragment runs differently in the two languages? I would include cases where order or operation or operator precedence was defined in one languge but undefined in the other but exclude cases where it was undefined in both.

I would be particulary interested in any development tools which could identify such fragments.

@Thomas. Thanks. J# is not an option - the code is mandated to be in C#. What does "this" refer to in your comment?

like image 410
peter.murray.rust Avatar asked Dec 14 '22 02:12

peter.murray.rust


2 Answers

One example - Java runs variable initializers after the superclass constructor. C# runs them before. This affects things if the superclass constructor then calls a virtual method overridden in the class in question. (This is generally a bad idea, but it happens.)

Then of course there's generics, which are very, very different. For example:

public class Foo<T>
{
    static int counter;
}

In Java there's one counter variable. In C# there's one per constructed type, so Foo<string>.counter and Foo<int>.counter are independent.

I'm afraid I don't know of any tools to identify this kind of thing.

I've done a certain amount of porting Java to C# myself, and I think it's important to try to make the resulting code as idiomatically "sharpy" as you can. Things like converting getters and setters to properties and sometimes indexers, for example. Implementing IDisposable where appropriate... things like that.

like image 148
Jon Skeet Avatar answered Dec 16 '22 16:12

Jon Skeet


Converting from Java to C# is difficult not only because of language difference, but because of not compatible base libraries. As for me, the best way to convert from Java to .Net is using IKVM - an implementation of Java for Mono/.NET

like image 43
macropas Avatar answered Dec 16 '22 17:12

macropas