Using Value Types
In the Java language, primitive types such as byte, int, boolean, char, short, long, float, and double are value types. All other types are reference types. In other .NET Framework languages, value types other than these can be defined. Visual J# provides extensions to the Java language to allow these value types defined in other .NET Framework languages to be used in J# code, and in Visual J# 2005, J# also enables value types to be authored in the language.
Value types are different from reference types in several ways. The following statements are true about value types:
Value types are stored on the stack, not the heap.
Value types are passed by value, not by reference.
Value types are copied as whole objects when assigned, rather than having only the reference copied.
When compared for equality, the entire object of a value type is compared for a match, rather than just the reference.
Value types cannot be derived from.
Value types do not require constructors.
For more information, see Value Types in the Common Type System.
The Visual J# compiler allows you to use value types defined in the .NET Framework or other user-defined assemblies. Instances of value types can be directly used in Visual J# as Object. The Visual J# compiler implicitly does the necessary boxing; when a value type is assigned to a variable of type Object, a proxy object is created and wrapped—boxed—around the value type. Similarly, when an object is cast to a value type, the compiler performs the unboxing, extracting the value type from the object wrapping. Boxing takes place automatically for value types defined in J# or other languages, but not for Java-language primitive types. For more information, see Using Value Types Corresponding to Primitive Types and User-Defined Value Types
Example
// vjc_valuetypes1.jsl
import System.*;
public class MyClass
{
public static void main(String [] args)
{
// DateTime is a value type; use it like a reference type.
DateTime dt = new DateTime();
dt = DateTime.Parse("01/01/2002 12:00");
// Automatically box value type dt to System.Object.
System.Object obj = dt;
// Obj unboxed to the value type DateTime.
DateTime dt2 = (DateTime) obj;
dt2 = DateTime.Parse("01/01/2003 12:00");
}
}
In this code, DateTime
is a value type defined in the .NET Framework library. Although the syntax is the same as for a reference type, the code generated is very different since operations on the value type are stack-based, not heap-based. There is a performance advantage over using a reference type since the operations of boxing and unboxing are not required, and since the value type resides on the stack, not the heap, accessing it does not require an indirection.
See Also
Reference
Syntax for Targeting the .NET Framework
Value Types (C# Reference)
Property and Event Exposure