views:

383

answers:

3

I am manually converting code from Java to C# and struggling with (what I call) primitive types (see, e.g. http://stackoverflow.com/questions/1597154/do-autoboxing-and-unboxing-behave-differently-in-java-and-c). From the answers I understand that double (C#) and Double (C#) are equivalent. double (C#) can also be used in containers, e.g. as a key in a Dictionary (whereas double (Java) cannot).

  1. Is double (C#) a primitive or an object?
  2. If it's a primitive what makes it behave differently from double (Java)?

double (C#) cannot be set to null unless it is made nullable.

  1. Is double? (C#) equivalent to Double (Java)? Are they both referred to as objects?

(Is the use of the term "first-class object" useful in this discussion?)

+8  A: 

Nullable<double> (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.)

Daniel Pryden
A: 

In C#, the best way to separate objects are by "Value Types" which are kinda like primitives - ints, bools, etc and "Reference Types" - classes etc.

Daniel A. White
+4  A: 
pst
I'd argue that it is more than an "aside", since this has a big implication re not boxing - i.e. `Nullable<int>` is a nullable, **non-boxed**, 32-bit signed integer.
Marc Gravell
You say "Recent versions of Java (1.5) add in explicit coercions" -- I think you have that backwards. Java has always had **explicit** conversions between primitive types and their object counterparts, but in Java 1.5 the language gained **implicit** conversions in the form of autoboxing/unboxing.
Daniel Pryden
@Daniel you are correct.
pst