PRB: No Automatic Conversion from Primitive Types to Object (325598)



The information in this article applies to:

  • Microsoft Visual J# .NET (2002)
  • Microsoft Visual J# .NET (2003)

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. "Boxing" 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 "More Information" 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 "More Information" 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.

REFERENCES

For more information about the Visual J# .NET syntax, visit the following Microsoft Developer Network (MSDN) Web site: For more information about the Common Intermediate Language specification, see the Tool Developers Guide documentation that is included with the .NET Framework Software Development Kit (SDK).

Modification Type:MajorLast Reviewed:8/7/2003
Keywords:kbprb KB325598