Export (0) Print
Expand All

5.2.4 Calling Methods on System::ValueType

Visual Studio .NET 2003

A __value class can directly call any function it explicitly implements without being boxed first. This includes any overrides of virtual member functions defined in System::ValueType.

Example

// __box5.cpp
// compile with: /clr
#using <mscorlib.dll>
using namespace System;

__value struct V {
   // override ValueType::ToString 
   String *ToString() { return i.ToString(); }
   int i;
};

int main() {
   V v = {10};
   Console::WriteLine(v.ToString());   // boxing not required
}

Output

10

To call a virtual function of System::ValueType that has not been overridden in the value type, boxing is required.

Example

// __box6.cpp
// compile with: /clr
#using <mscorlib.dll>
using namespace System;

__value struct V { int i; };

int main() {
   V v = {10};  
   v.i = 10;
   // Console::WriteLine(v.ToString());   // C3610 boxing required
   Console::WriteLine(__box(v)->ToString());   // ok: prints typename V
}

Output

V

C++ primitive types follow the same rules for boxing as value types. For example, you do not need to box a C++ primitive type before calling methods on its underlying value type.

Example

// __box7.cpp
// compile with: /clr
#using <mscorlib.dll>
int main() {
   int i = 10;
   System::Console::WriteLine(i.ToString());   // no need to box
   System::Console::WriteLine((5).ToString());   // no need to box
}

Output

10
5
Note   The expression 5.ToString is syntactically incorrect due to C++ rules for token processing. Literal values should be surrounded by parentheses when invoking __value class methods on them.
Show:
© 2014 Microsoft