Are primitive types different in Java and C#?

后端 未结 3 1238
梦谈多话
梦谈多话 2020-12-29 10:08

I am manually converting code from Java to C# and struggling with (what I call) primitive types (see, e.g. Do autoboxing and unboxing behave differently in Java and C#). Fro

3条回答
  •  [愿得一人]
    2020-12-29 10:45

    Nullable (aka double?) in C# is not the same as a Double in Java.

    Before Java had autoboxing/unboxing, you had to manually convert between primitives and first-class objects:

    Double dblObj = new Double(2.0);
    double dblPrim = dblObj.doubleValue();
    

    In Java 1.5 that changed, so you could just do:

    Double dblObj = 2.0;
    double dblPrim = dblObj;
    

    And Java would insert code to mirror the above example automatically.

    C# is different because there is an unlimited number of "primitive" types (what the CLR calls value types). These behave mostly like Java's primitives, using value semantics. You can create new value types using the struct keyword. C# has autoboxing/unboxing for all value types, and also makes all value types derive from Object.

    So you can use a value type (like double) where you would use any object reference (e.g. as a key in a Dictionary) and it will be boxed if necessary, or else just used directly. (C#'s Generics implementation is good enough to avoid boxing in most circumstances.)

提交回复
热议问题