Do autoboxing and unboxing behave differently in Java and C#

前端 未结 2 442
天涯浪人
天涯浪人 2021-01-04 21:47

I am manually converting code from Java (1.6) to C# and finding some difficulty with the behaviour of primitives (int and double). In C# it appears that almost all conversio

相关标签:
2条回答
  • 2021-01-04 22:36

    In your C# example there is no boxing or unboxing (and autoboxing) happening. double is just an alias for the struct Double.

    In Java, the boxing is necessary. Because of type erasure, you can't create a List<double>, only List<Double>. At compile time, List<?> becomes List<Object> and boxing/unboxing will need to take place so you can add a native type variable to a List<Object> or assign a native variable to an element of the List.

    0 讨论(0)
  • 2021-01-04 22:44

    In C#, double and Double are exactly the same thing (as long as you haven't created your own type called Double, which would be stupid).

    double is defined as an alias to global::System.Double. As such, there is no boxing here.

    In java, Double is a boxed double, with type-erasure being a key part of the generics implementation.

    0 讨论(0)
提交回复
热议问题