Microsoft KB Archive/325598

= PRB: No Automatic Conversion from Primitive Types to Object =

Article ID: 325598

Article Last Modified on 8/7/2003

-

APPLIES TO


 * Microsoft Visual J# .NET 2003 Standard Edition
 * Microsoft Visual J# .NET 2003 Standard Edition

-



This article was previously published under Q325598



SYMPTOMS
When you expect automatic conversion in Visual J# .NET, such as when you pass a Java language primitive type as an object or in assignments, the automatic conversion does not work, although other language compilers support automatic conversion.

You may receive compiler error messages such as the following:

error VJS1223: Cannot find method 'Add(int)' in 'System.Collections.ArrayList'

or

error VJS1301: Type 'int' is not assignable to 'Object'



CAUSE
The Java language syntax does not allow you to assign primitive types directly to Object. &quot;Boxing&quot; is only supported for underlying value types behind Java language primitive types, such as System.Int32 for a Java language int.

For more information about the box instruction, see the &quot;More Information&quot; section.



RESOLUTION
To work around this problem, Java language primitive types must first be cast to their underlying value type. For an example, see the &quot;More Information&quot; section.



STATUS
This behavior is by design.



MORE INFORMATION
The following code sample shows the correct and incorrect syntax for conversion to Object: // incorrect - these will throw errors. new System.Collections.ArrayList.Add(10); Object obj = 10;

// correct - these work. new System.Collections.ArrayList.Add((System.Int32)10); Object obj = (System.Int32) 10; The following is an excerpt from the Common Intermediate Language (CIL) specification (Partition III):

The box instruction converts the 'raw' valueType (an unboxed value type) into an instance of type Object (of type O). This is accomplished by creating a new object and copying the data from valueType into the newly allocated object.

