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

前端 未结 4 584
轻奢々
轻奢々 2021-01-06 07:27

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

4条回答
  •  逝去的感伤
    2021-01-06 08:24

    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
    {
        static int counter;
    }
    

    In Java there's one counter variable. In C# there's one per constructed type, so Foo.counter and Foo.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.

提交回复
热议问题