APPENDIX ■ ■ ■ Quick Reference

This appendix covers the new keywords introduced in C++/CLI, specifies which are also reserved words, and defines and lists contextual keywords and whitespaced keywords. This appendix includes a reference table for features available in native, mixed, pure, and safe modes. You’ll also find a summary of the syntax introduced in C++/CLI.

Keywords and Contextual Keywords Some new keywords were introduced in the C++/CLI bindings. Many new keywords introduced in C++/CLI are sensitive to the context in which they are used, so as to avoid creating new reserved words in order not to interfere with existing identifiers. When used in the proper syntactic position, contextual keywords are interpreted with the keyword meaning. When used in any other posi- tion, they may be used as identifiers. This enables your code to continue to use a variable that happens to collide with a C++/CLI contextual keyword without any special marking or modifi- cation. This also enables C++/CLI to use keywords that otherwise would be common variable names. There are several new keywords that are not contextual, as described in Table A-1: gcnew, generic, and nullptr. Table A-2 shows the new contextual keywords.

Table A-1. C++/CLI Keywords Keyword Description Usage gcnew Allocates instances of reference R^ r = gcnew R(); types on the garbage-collected (managed) heap generic Declares a parameterized type generic ref class G { /* ... */ }; (generic) that is recognized by the runtime nullptr Evaluates to the null value for R^ r = nullptr; a pointer, indicating an unassigned pointer

355 356 APPENDIX ■ QUICK REFERENCE

Table A-2. C++/CLI Contextual Keywords Contextual Description Usage Keyword abstract Declares a class that has some ref class Base abstract { /* ... */ }; unimplemented methods, used as a base class. Objects cannot be instan- tiated from this class. When used on a method, declares that the method will not be implemented. delegate Declares an object that represents delegate void MyDelegate(int); a type-safe . event Declares an event, an occurrence event EventHandler ClickEvent; that triggers method calls. finally Captures program flow after a finally { /* ... */ } try/catch block. in Used in the for each statement. for each (R^ r in collection) { /* ... */ } initonly Specifies a field that can only be initonly int i; modified in a constructor. internal Specifies that access to a member public ref class R is restricted to within an assembly. { internal: void f(); } literal Specifies a value that is a literal int SIZE = 150; literal constant. override Indicates that a function is intended virtual int f(int a, int b) override; to be a virtual override of the base class function of the same name. property Declares a field-like member property int P; on a type. sealed Indicates a type that cannot be used virtual int f(int a, int b) sealed; as a base class or a method cannot be overridden. where Used in the declaration of generics generic where T : R to specify constraints on the types ref class G { /* ... */}; that may be used as type arguments for a generic type or function.

Whitespaced Keywords Some of the keywords in C++/CLI are two words containing whitespace, which are referred to as whitespaced keywords. For example, ref class is a whitespaced keyword. Spaces and tabs may be used between the two words, but comments (despite technically being whitespace after preprocessing) may not be used. Table A-3 lists the whitespaced keywords of C++/CLI. APPENDIX ■ QUICK REFERENCE 357

Table A-3. Whitespaced Keywords Whitespaced Description Usage Keyword enum class Declares an enumeration enum class Color { Red, Green, Blue}; with all members public enum struct Declares an enumeration enum struct Color { Red, Green, Blue }; with all members public for each Used to iterate over for each (R^ r in collection) { /* ... */ } collection classes interface class Declares an interface with interface class I { /* ... */ }; all members public interface struct Declares an interface with interface struct I { /* ... */ }; all members public ref class Declares a managed type ref class R { /* ... */ }; with private default accessibility ref struct Declares a managed ref struct S { /* ... */ }; struct with public default accessibility value class Declares a value type value class V { /* ... */ }; with private default accessibility value struct Declares a value type value struct S { /* ... */ }; with public default accessibility

Keywords As Identifiers You can specify __identifier to use a keyword as an identifier. Use it when you migrate existing code to C++/CLI that uses one of the new keywords: gcnew, generic, or nullptr, or if you are dealing with another code from another language that has an identifier that matches a C++/CLI keyword, as in Listing A-1.

Listing A-1. Using __identifier

// identifier.cpp using namespace System; int main() { int __identifier(switch) = 10;

__identifier(switch)++; 358 APPENDIX ■ QUICK REFERENCE

switch( __identifier(switch) ) { case 10: break; case 11: Console::WriteLine("Switch is {0}", __identifier(switch)); break; default: break; }

}

The output of Listing A-1 is as follows:

Switch is 11

The following sections describe features not otherwise covered in this book: how to detect CLR compilation, and XML documentation comments.

Detecting CLR Compilation Listing A-2 demonstrates how to detect CLR compilation.

Listing A-2. Detecting CLR Compilation

// detecting_clr.cpp #include int main() { #ifdef _MANAGED System::Console::WriteLine("Must be compiling with /clr..."); #else printf("Not compiling with /clr."); #endif }

The output of Listing A-2 is as expected with or without the /clr option:

C:\code\appendix>cl /clr detecting_clr.cpp Microsoft (R) C/C++ Optimizing Compiler Version 14.00.50727.42 for Microsoft (R) .NET Framework version 2.00.50727.42 Copyright (C) Microsoft Corporation. All rights reserved. APPENDIX ■ QUICK REFERENCE 359 detecting_clr.cpp Microsoft (R) Incremental Linker Version 8.00.50727.42 Copyright (C) Microsoft Corporation. All rights reserved.

/out:detecting_clr.exe detecting_clr.obj

C:\code\appendix>detecting_clr Must be compiling with /clr...

C:\ code\appendix>cl detecting_clr.cpp Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 14.00.50727.42 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. detecting_clr.cpp Microsoft (R) Incremental Linker Version 8.00.50727.42 Copyright (C) Microsoft Corporation. All rights reserved.

/out:detecting_clr.exe detecting_clr.obj

C:\ code\appendix>detecting_clr Not compiling with /clr.

XML Documentation XML files may be generated from code comments written in the CLR XML doc format by writing comments in the format in code and compiling with the /doc compiler option. You can use these XML files to generate formatted documentation. The tool xdcmake.exe is used to generate the XML files from doc comments. Table A-4 lists the XML tags available.

Table A-4. XML Doc Comment Reference XML Tag Description inline code Inline code code block Lines of code example section Defines a section containing text description and an optional code example description Specifies exceptions that may be generated Includes XML comments from a file Defines a bulleted or numbered list or table 360 APPENDIX ■ QUICK REFERENCE

Table A-4. XML Doc Comment Reference (Continued) XML Tag Description text Defines a paragraph description Describes a function parameter Specifies a hyperlink to the parameter Specifies access (e.g., public) description Specifies the detailed description description Specifies the return value information Specifies a cross-reference Lists additional references

text Specifies text that gives a brief synopsis description Specifies a property description

Listing A-3 illustrates the use of the XML comment format and the generation of XML documentation from the comments.

Listing A-3. Using XML Documentation

// xml_comments.cpp // compile with: /LD /clr /doc // then run: xdcmake xml_comments.xdc

using namespace System;

/// Ref class R demonstrates XML Documentation Comments. ///

A class demonstrating documentation comments /// A detailed description of R goes into the remarks block /// public ref class R { public: /// F is a method in the R class. /// You can break the comments into paragraphs. /// for related information. /// /// void F(int i) {} APPENDIX ■ QUICK REFERENCE 361

/// The method G is a method in the R class. ///

Counts the number of characters in two strings. /// Description for s1 /// Description for s2 /// The sum of the length of two strings. int G(String^ s1, String^ s2){ return s1->Length + s2->Length; } };

Listing A-3 is compiled with cl /clr /doc /LD xml_comments.cpp

The documentation comments are generated with xdcmake xml_comments.xdc

The resulting xml_comments.xml file, with some minor whitespace alterations, is as follows:

xml_comments The method G is a method in the R class.

Counts the number of characters in two strings. Description for s1 Description for s2 The sum of the length of two strings. F is a method in the R class. You can break the comments into paragraphs. for related information. Ref class R demonstrates XML Documentation Comments. A class demonstrating documentation comments A detailed description of R goes into the remarks block 362 APPENDIX ■ QUICK REFERENCE

It is up to you to then render this in the desired user-friendly documentation format. For example, you could generate documentation in various formats using a tool such as Sandcastle, available from the Microsoft download center (http://www.microsoft.com/downloads).

Summary of Compilation Modes This book has covered many aspects of the various modes, but not all. Table A-5 summarizes the features available in each compilation mode.

Table A-5. Features Available in Various Compilation Modes Feature Native Mixed Pure Safe Define and use native types Yes Yes Yes No Define and use managed types No Yes Yes Yes Define native functions Yes Yes No No Define managed functions No Yes Yes Yes Native instructions* Yes Yes No No Managed instructions (IL) No Yes Yes Yes Build 32-/64-bit No No No Yes agnostic assemblies Use the NET Framework No Yes Yes Yes Use the CRT Yes Yes MSIL CRT No Use the Standard C++ Library Yes Yes MSIL version No Use ATL Yes Yes No No Use MFC Yes Yes No No App domain aware No No Yes Yes Reflection on built assembly No DLLs only Yes Yes Call functions via P/Invoke N/A Yes Yes Yes Use unsafe casts** Yes Yes Yes No Include native header Yes Yes Depends No on header Include managed header No Yes Yes Yes #using managed assembly No Yes Yes Yes #import COM typelib/DLL Yes Yes No No Compile C code Yes No No No Floating-point control Yes No No No (__controlfp, etc) std::set_terminate and SIGTERM Yes No No No APPENDIX ■ QUICK REFERENCE 363

Table A-5. Features Available in Various Compilation Modes Feature Native Mixed Pure Safe Nonvirtual calls to virtual functions Yes Yes Yes No† Command-line arguments in main Yes Yes Yes No Throw exceptions by value Yes Yes Yes No Pointer arithmetic on No Yes Yes No interior pointers Explicit keyword For For For No constructors conversions conversions Export native functions Yes Yes No No (__declspec(dllexport)) Import native functions Yes Yes Yes No (__declspec(dllimport)) Custom alignment Yes No No No (__declspec(align)) __declspec(naked) Yes Yes Yes No #pragma unmanaged No Yes No No #pragma pack Yes Yes Yes No __based Yes Yes Yes No Structured Exception Handling Yes†† Yes†† Yes†† No

* Inline asm, most compiler intrinsics ** Including downcasts with static_cast and all uses of reinterpret cast † Not detected by Visual C++ 2005 compiler †† Not in the same function as managed or C++ exception handling Syntax Summary In these examples, assume R is a reference type (ref class) and V is a value type (value class), I is an interface (interface class), and P is a property (property int P). Also assume r is a handle to R and v is an instance of V. Assume i, j, and k are integer fields or local variables, s is a handle to String, and ai is a one-dimensional managed array of integers. Assume Base and Derived are reference classes in an inheritance relationship. Assume d is typed as a handle to Derived and b has type handle to Base, but could be an actual instance of a Base or Derived object, or nullptr. The order of the examples is the order in which they are covered in the text.

Handle

R^ r; // Declare a handle. R r1 = *r; // Dereference a handle. i = r1->P; // Access a member using the -> operator. 364 APPENDIX ■ QUICK REFERENCE

Tracking Reference

// Declare a tracking reference and initialize to dereferenced handle. R% rref = *r; i = rref.P; // Access a member using the . operator.

The gcnew Keyword

R^ r = gcnew R; // gcnew using default constructor r = gcnew R(); // gcnew using default constructor r = gcnew R(100, "xyz"); // gcnew with args

The nullptr Keyword

r = nullptr; // Set handle to null.

The main Method

int main(array^ args) { /* body of main method */ return i; // optional return statement }

Managed Arrays

// Declare an array of reference types but don't create it. array^ refArray; // Declare array of value types but don't create it. array^ valueArray; // Declare and create 1D array of integers with size // determined by given initial values. array^ ai = gcnew array { 0, 1, 2, 3 }; // Declare and create 1D array of integers with given size. array^ ai = gcnew array(4); // array with two dimensions, four by two array^ ai2d = gcnew array(4, 2) { { 0, 1 }, { 2, 3 }, { 4, 5 }, { 6, 7} };

The for each Statement

// for each statement for array of integers for each (int i in ai) { /* body */ } // for each statement for collection of ref objects for each (R^ r in rCollection) { /* body */ } APPENDIX ■ QUICK REFERENCE 365

Reference Classes ref class R { /* body */ }; // public abstract ref class inheriting from Base [ SomeAttribute ] public ref class R abstract : Base { /* class body */ };

Value Classes value class V { /* class body */ }; // value class inheriting from interface I [ SomeAttribute ] public value class V : I { /* class body */ };

Enum Classes

// enum with some values enum class MyEnum { Zero, One, Two, Three = 3, Ten = 10 }; // enum with char as underlying type enum class MyEnum : char { Zero, One, Two };

Interface Classes interface class I { /* class body */ }; public interface class I : IBase { /* class body */ };

Safe Cast try { d = safe_cast(b); } catch(InvalidCastException^ e) { // Handle the exception. }

Dynamic Cast d = dynamic_cast(b); if (d == nullptr) { /* cast failed*/ }

Static Cast unsigned int u; i = static_cast(u); // no overflow check int* pi; void* pv; pi = static_cast(pv); 366 APPENDIX ■ QUICK REFERENCE

Const Cast

const wchar_t* cwcs = L"xyz"; wchar_t* wcs = const_cast(cwcs);

C-Style Cast

Base^ b = gcnew Derived(); try { d = (Derived^) b; // evaluates to safe_cast

Access Modifiers

public ref class R { };

private ref class R { };

ref class R { public: void F() {}

private: void G() {}

protected: void H() {}

internal: void I() {}

protected private: void K() {}

protected public: void L() {} }; APPENDIX ■ QUICK REFERENCE 367

Stack Semantics Declaration void f() { R r; r.P = 100; // Use the . operator to access a member. }

Initonly Fields ref class R { initonly int i; public: R() i(5) { } };

Literal Fields ref class R { literal int SIZE = 100; literal String^ NAME = "Test"; };

Static Constructor ref struct R { private: static R() { /* body */ } };

Finalizer ref struct R { ~R() { this->!R(); } // implements IDispose::Dispose !R() { /* finalizer body */ } }; 368 APPENDIX ■ QUICK REFERENCE

Properties

ref struct R { property int P1; // trivial property // nontrivial property with int backing store int value; property int P2 { int get() { return value; } void set(int i) { value = i; } } // indexed property array^ names; // backing store property String^ P[ int ] { String^ get(int index) { return names[index]; } void set(int index, String^ s) { names[index] = s; } } // default indexed property property String^ default[ int ] { String^ get(int index) { return names[index]; } void set(int index, String^ s) { names[index] = s; } } };

Delegates

// Declare delegate type. delegate void MyDelegate(int, String^);

void f() { // Create delegate to method F on object r. MyDelegate^ del = gcnew MyDelegate( r, &R::F); del += gcnew MyDelegate(r, &R::G); // Add target function. del -= gcnew MyDelegate(r, &R::G); // Remove target function. del += gcnew MyDelegate(&R::StaticMethod); // Add static method. del(100, "xyz"); // Invoke delegate. del->Invoke(200, "abc"); // Invoke delegate. } APPENDIX ■ QUICK REFERENCE 369

Events ref class R { public: event EventHandler^ E1; // trivial event EventHandler^ evt; event EventHandler^ E2 { void add(EventHandler^ e) { evt += e; } void remove(EventHandler^ e) { evt -= e; } void raise(Object^ o, EventArgs^ args) { evt(o, args); } }

void F(Object^ o, EventArgs^ args) { /* event handler body */ }

void f() { E1 += gcnew EventHandler(r, &R::F); } };

Static Operators ref class R { // member operator: R^ operator+(int i) { /* body */ }

// static operator: static R^ operator+(int i, R^ r) { return r + i; // Call member operator + (above). } }; 370 APPENDIX ■ QUICK REFERENCE

Virtual Functions

ref struct Base { virtual int f(int i) { /* ... */ } virtual void g(String^ s) { /* ... */ } }; ref struct Derived : Base { virtual int f(int i) override { /* body */ } // Override Base::f. virtual void g(String^ s) new { /* body */ } // no override };

Abstract Classes

ref struct R abstract { virtual void F(int, String^) abstract; };

Abstract Methods

ref struct R { virtual void F(int, String^) abstract; };

Sealed Classes

ref struct Base { virtual void F(int i) { /* method body */} };

ref class Derived sealed : Base { public: virtual void F(int i) override { /* method body */ } };

Sealed Methods

ref struct Base { virtual void F(int i) { /* body */ } }; ref struct Derived : Base { virtual void F() sealed { /* body */ } }; APPENDIX ■ QUICK REFERENCE 371

Interface Implementation interface class I { int F(int i, String^ s); void g(); }; ref class R : I { public: virtual int F(int i, String^ s) { /* implement I::F */ } virtual void g() { /* implement I::g */ } };

Explicit Interface Implementation interface class I { int F(int i, String^ s); void g(); }; ref class R : I { public: virtual int F(int i, String^ s) = I::F { /* implement I::F */ } virtual void x() = I::g { /* implement I::g */ } // possibly different name };

Exceptions

R^ r = gcnew R(); try { if ( /* ... */ ) throw gcnew SomeException(); } catch(SomeException^ e) { // Handle SomeException;. } catch(SomeOtherException^ e) { // Handle SomeOtherException. } 372 APPENDIX ■ QUICK REFERENCE

finally { // Clean up code. if (r != nullptr) delete r; }

Attributes

// attribute intialized with constructor applied to method f [ SomeAttribute("Arg1", "Arg2") ] void f(); // attribute initialized with public properties P and Q [ SomeAttribute( P = "Arg1", Q = "Arg2") ] void f(); // attribute applied to return value (target syntax) [ returnvalue : SomeAttribute() ] R^ f(int i);

Type Identification

Type^ type = R::typeid; // Get static type from class. Type^ type = r->GetType(); // Get dynamic type from object.

Managed Template Classes

template // or template < class T> public ref class R { T t; // type parameter as a member public: // method using type parameter in parameter list void f(T t, array^ a) { /* method body */ } /* class body */ };

Managed Template Functions

template < typename T > int TemplateFunction(T t) { /* body */ };

Generic Classes

generic // or generic < class T> where T : I ref class G { /* body of generic class */ }; APPENDIX ■ QUICK REFERENCE 373 generic < typename T, typename U > where T : R, gcnew() // multiple constraints on one type parameter where U : value class // constraints on multiple type parameters public ref class G abstract { /* body of generic abstract class */ T t; // reference type handle U u; // value type object public: G() { t = gcnew T(); } };

Generic Functions generic [ SomeAttribute ] // Attributes go after the generic preamble. T f(array^ at) { /* method body */ } int g() { array^ a; // call generic function return f(a); }

Interior Pointers and Pinning Pointers ref struct R { array^ a; public: int f() { int sum = 0; // interior pointer interior_ptr pi = &a[0]; for (int i = 0; i < a->Length; i++) { // using pointer arithmetic sum += *pi++; } return sum; } 374 APPENDIX ■ QUICK REFERENCE

int g() { // pinning pointer pin_ptr pinp = &a[0]; return native_function(pinp); } };

The auto_handle Template

#include using namespace msclr; auto_handle auto_r = R::ReturnHandleToNewR();

The lock Class

#include using namespace msclr; void f(R^ r) { lock lockr(r); /* sensitive code using r */ } // stack semantics, lock released

The gcroot Template

#include using namespace msclr; class N { gcroot r; void f() { r = gcnew R(); r->F(); // Call method F on r. } }; APPENDIX ■ QUICK REFERENCE 375

The auto_gcroot Template

#include using namespace msclr; class N { auto_gcroot r; void f() { r = gcnew R(); r->F(); // Call method F on r. } }; // r's destructor is called when containing object is deleted. Index

■Symbols and Numerics access control ! character, finalizers, 161 access levels for classes, 156–157 % operator/symbol, 52–53 interfaces, 236 C++/CLI stack semantics, 68 interfaces and access control, 244 creating handle to object using %, 66 protected access control specifier, 183 passing value types as handles, 68 accessibility modifiers, 37, 156, 157 passing value types by reference, 65 access modifier syntax, 366 tracking references, 55 accessor (add and remove) methods of & (address-of) operator, 52 events, 191, 193 passing by reference in C++, 60 reserved names (add_E, remove_E), 203 * operator, 54 accessor (get and set) methods of properties, 173–177 + operator, 79, 80, 205 applying virtual keyword, 222, 223 += operator, 22, 184, 194 different ways of defining properties, 22 -= operator, 22, 184, 185 interfaces with properties and events, 240 .NET Developer Platform (NDP), 29–41 reserved names (get_P, set_P) for ^ character see caret (^) character properties, 203 ^% indirection setting but not getting properties, 183 passing handle by reference using, 54 using virtual accessors, 223 64-bit programming AccessViolationException, 260 processor architecture dependence, 32 Activator class ■A CreateInstance method, 280 abstract base classes add method, event handlers interface class compared, 19 customizing, 191, 193, 194 abstract classes, 219–220 declaring events and event handlers, 193 declaring abstract classes, 219, 220 reserved names (add_E) for events, 203 declaring any function abstract, 219 using delegate unrelated to interfaces compared, 220, 235–236 EventHandler, 197 syntax, 370 addition operator, 79, 80 using abstract and sealed keywords, 221 addressable entities, 56 abstract keyword, 219, 220, 356 addresses, arrays, 93 abstract methods, 370 address-of operator for managed types, 52

interior pointers, 339 377 378 ■INDEX

AdjustPointTotals method, Scrabble associative array, 308 game, 137 converting string to character array, 78 aggregate types, 12–14 copying, 102–103 al.exe see assembly linker creating one-dimensional arrays, 96 alignment specifier, 82 deletion and insertion of elements, 108 AllowMultiple property, 279 equality of, 106–107 AppDomain class, 284 for each traversing arrays, 98 application domains, 283–284 generic array as parameter, 287 compilation modes available for, 362 going past the end of, 100 multiple application domains, 283 indexed properties, 177 architecture initializing array elements with processor architecture dependence, 32 constructors, 95 argc arguments, main method, 9 initializing, 93–95 ArgumentException, 260 initializing part of, 96 iterating over dictionary collection, 309 interior pointers traversing arrays, 99 proliferation of exception types, 269 iterators traversing arrays, 97 arguments Length property, 95 argument lists of variable length, 107 managed array class members, 103–106 CLS compliant alternative to varargs, 322 managed arrays, 9, 92–110 command line arguments, 9 accessing elements, 93 ArithmeticException, 260 declaring, 92 Array class using, 14 Copy method, 102 native and managed arrays compared, IList interface, 103 100–101 managed array class members, 103–106 navigating, 97–100 methods, 104 parameter arrays, 107–108 properties, 103 passing array of inconsistent size, 101 ArrayList class, 108–110, 305–308 passing by reference, 102 iterating with for each and with index, 307 pitfalls treating object on heap as if on stack, 51 trapping invalid cast exception, 306 rank, 93 using generic list, 110 self-knowledge, 95 using weakly typed/nongeneric ArrayList, 305 sorting and searching, 105 arrays, 92–110 sparse array, 26 array address, 93 zero-based indices, 93 array of handles in Scrabble game, 127 “as-a” relationship ArrayList class, 108–110 abstract classes and interfaces compared, 235 arrays as parameters, 101–102 as_friend modifier, 39 arrays in classes, 108 AsReadOnly method, Array class, 104 ■INDEX 379 assemblies assembly manifest, 33–37 assembly linker, 33 viewing metadata with ILDasm.exe, 34–37 assembly using template type in public ASSEMBLYRESOURCE command-line interface, 311 option, 41 compilation modes available for, 362 assignment behavior controlling access, 39 reference and value types compared, 118 friend assemblies, 39 assignment operator (=) intra-assembly code, 312 object semantics for reference types, 43 introduction, 33 assignment statements, 56 linking object files of different modes, 318 associative array, 308 loading assembly and reflecting on AsyncCallback class, 189 types, 280 asynchronous delegates, 188–190 metadata, 33 checking function completion, 189 Find it faster at http://superindex.apress.com at it faster Find Find it faster at http://superindex.apress.com at it faster Find mixing managed/native classes/types, 318 AsyncResult class, 189 modules, 33 ATL (Active Template Library) multifile assemblies, 41 clr:pure mode, 31 passing template class types over compilation modes for, 362 assembly boundary, 311 atomic number, 12 referencing, 37, 39 Attribute class, 271 reflection writing tools giving information creating custom attributes, 277–279 on, 282 GetCustomAttribute method, 279 resources and, 41 attribute classes/constructors/parameters, 271 signed assemblies, 41 attribute properties, 279 using template from another assembly, 314 Attribute suffix, omitting, 271 using template in another assembly, 312 attributes, 270–279 using wrapper from C# assembly, 337 assembly attributes, 40, 276–277 assembly attributes, 276–277 attribute target, 270 friend assemblies, 39 AttributeUsageAttribute, 279 introduction, 40 creating custom attributes, 277–279 assembly boundaries DllImport attribute, 322 managed templates and generics how attributes work, 270 compared, 316 inheritance, 271 Assembly class initializing attribute with properties, 278 GetTypes method, 279 MarshalAs attribute, 328 interfaces and dynamically loaded types, metadata, 270 255, 257 module attributes, 276–277 LoadFrom method, 279 NonSerialized attribute, 273 reflection calling methods, 284 Obsolete attribute, 271–272 assembly linker, 40, 41 Out attribute, 272–273 380 ■INDEX

querying object attributes at runtime, 279 ■C Serializable attribute, 273 C code serialization attributes, 273–275 compilation modes available for, 362 syntax, 372 c tag, XML documentation, 359 AttributeTargets property, 279 C# AttributeUsageAttribute, 279 consuming wrapped global function in, 320 auto_gcroot template, 159 C++ destructor, 160 aggregate types, 12 gcroot and auto_gcroot compared, 342 creating interface in C++, 320 syntax, 375 “Hello World” program, 5 auto_handle template, 58–60, 374 interop using C++ source code, 318 ■B interop with C++ exceptions, 352–354 use of “classic C++” in this book, 2 bag list, Scrabble game, 131 using native libraries without P/Invoke, 329 base classes C++/CLI calling base class constructor, 226 classes and structures compared, 9 explicitly specifying implicit base classes, 237 enabling standard extensions, 3 name collisions in inheritance “Hello World” program, 6 hierarchies, 212 interoperability, 317 order of initialization, 227, 228 standard C++ functionality, 1 using virtual functions in constructor, 229 CalculateScore method, Scrabble game, 148 based keyword, 363 calling conventions BCL (base class library), 5 cdecl, 327 BeginInvoke method, Delegate class, clrcall, 347 188, 189 stdcall, 324 BinarySearch method, Array class, 104, 105 thiscall, 327 Boolean type, 11 CallingConvention property, DllImport boxed value types, 321 attribute, 326 boxing P/Invoke knowing calling convention, 324 generic collection classes, 290 carbon dating, 12 implicit boxing and unboxing, 45–47 CardEnumerator class integer types, 45 Current property, 249 literal values, 46 cards performance, 46 enumerating playing cards, 249 unboxing Object to integer, 46 caret (^) character value type converted to object, 46 handles, 7 value type inheritance, 212 using two handle symbols, 10 value types, 44 using managed array type, 15 Byte type, 11 ■INDEX 381 casts access levels for classes, 156–157 const_cast, 209 ArrayList class, 305–308 C-style casts, 208, 209 arrays in classes, 108 dynamic_cast, 208, 209 AsyncCallback class, 189 Enum class object conversions, 112 AsyncResult class, 189 explicit casts, 206 Attribute class, 271 implicit boxing and unboxing, 45 calling base class constructor, 226 inheritance hierarchies, 233–234 class constraints, 297–298 InvalidCastException, 210, 260 class destruction and cleanup, 160–161 reinterpret_cast, 209, 210 Complex class, 203 safe_cast, 209, 210, 112 Dictionary class, 308 static_cast, 208, 209 Enum class, 111 trapping invalid cast exception, 306 enumeration classes, 17–18 Find it faster at http://superindex.apress.com at it faster Find catching exceptions, 269 EventArgs class, 201 throwing objects, not exceptions, 268 EventHandler class, 199 cdecl calling convention, 327, 347 EventReceiver class, 200 P/Invoke knowing calling convention, 324 EventSender class, 200 chaining expressions involving properties, 174 Exception class, 260 Char type, 11 Exception classes, 262–263 characters indexed properties, 177–184 converting string to character array, 78 interface classes, 19–20 Characters class, Scrabble game, 128 interface name collisions, 241 CharSet parameter, DllImport attribute KeyValuePair class, 309 calling Win32 function in C++/CLI, 323 Marshal class, 328 CIL (Common Intermediate Language) see IL multiple inheritance of class types, 211 class constructor see static constructors order of initialization, 227 class keyword properties, 173–177 type parameters, generics, 285 indexed properties, 177–184 whitespaced keywords, 357 reference classes, 14–15 classes sealed class syntax, 221 .NET class features, 173–210 sealed classes, 220–222 delegates, 184–190 serialization and deserialization, 275 events, 191–203 StringBuilder class, 84–85 indexed properties, 177–184 structures compared, 9, 117 operator overloading, 203–210 Type class, 279 properties, 173–177 using virtual functions in constructor, 229 abstract classes, 219–220 value classes, 15–17 abstract sealed class, 221 classic C++ interfaces compared, 235 use of term in this book, 2 382 ■INDEX

cleanup collections class destruction and cleanup, 160–161 backing property with collection, 180 handling managed and unmanaged collection owning and deleting objects, 302 resources, 167 Collections namespace, 304 cleanup code Collections::Generic namespace, 304 finally block, 263, 269 COM interop, 318, 328–329 Clear method, Array class, 104 interop with COM HRESULTs, 354 CLI programming, 5 COM libraries abstract classes and interfaces import directive, 37 compared, 235 Combine method, Delegate class, 186 interface inheritance model, 241 command line arguments managed templates and generics compilation modes available for, 363 compared, 316 using, 9 primitive types, 11–12 comments, XML documentation, 359 Clone method, Array class, 104 Common Intermediate Language (CIL), 3 CLR (common language runtime) common type system see CTS CLR XML doc format, 359 Compare method, String class, 80, 81 detecting CLR compilation, 358 CompareOrdinal method, String class, 81 garbage collection, 1 CompareTo method link.exe, CLR programming, 40 IComparable interface, 246 setting compilation mode, 30 String class, 80, 81 virtual machine, 3 comparing strings, 76, 80–81 clr compiler option see mixed mode compilation modes, 3 clr:oldSyntax compiler option see managed extensions syntax detecting CLR compilation, 358 clr:pure compiler option see pure mode features available for all modes, 362 clr:safe compiler option see safe mode Visual C++ 2005, 30–32 clrcall calling convention, 347, 348 compiler options CLS (Common Language Specification), 321 clr (mixed mode), 31 code substitutions, indexes, 81 clr:oldSyntax, 32 code tag, XML documentation, 359 clr:pure (pure mode), 30 Collect method, GC class clr:safe (safe mode), 30 pitfalls of finalizers, 170 doc, 359 using destructor and finalizer, 163 FU (Force Using), 38 collection classes LD, 39 .NET Framework container types, 304 LN, 33 ArrayList class, 305–308 compilers Dictionary class, 308 compiler restrictions on generic types, 289 generic collection classes, 290–295 how compilers understand expressions, 56 generic/nongeneric container classes, 304 managed templates and generics compared, 315 using collection class interfaces, 305 ■INDEX 383 compile-time constants constructors const correctness, 126 attribute constructors, 271 literal fields, 123, 124 calling base class constructor, 226 static constants, 124 copy constructors, 55, 121 Complex class default constructors, 118 defining static operators, 205 exceptions in, 265–266 representing complex numbers, 203 inheritance, 226–228 compound assignment operators (+=, -=, initializing array elements with, 95 etc.), 22 initonly fields, 124 Concat method, String class, 76 managed types, 118 concatenation of strings, 76, 79 order of initialization, 227 ConfirmPlay method, Scrabble game, 144 reference and value types compared, 118 connections static constructors, 119–120 Find it faster at http://superindex.apress.com at it faster Find pitfalls of finalizers, 170 String class, 76 Console class, 86–87 virtual functions in, 228–230 basic I/O functions, 86 container classes see collection classes properties exposed for container types, .NET Framework, 304 stdin/stdout/stderr, 87 context switch, 327 ReadLine method, 87 thunk, 347 Scrabble game, 128 unnecessary context switches, 348 Write method, 86 using native libraries without P/Invoke, 330 WriteLine method, 81 contextual keywords see keywords const correctness, 126 conversion operators, 206–210 const fields, managed classes, 121 using explicit keyword with, 206–208 const reference, 55 conversions const_cast, 209, 366 enumerated types, 112 constants, 118, 123 explicit casts, 206 initonly fields, 124–125 handling managed and unmanaged ConstrainedCopy method, Array class, 104 resources, 167 constraints marshaling and, 159 adding to MyList and ListNode, 303 using native objects in managed types, 158 class constraints, 297–298 ConvertAll method, Array class, 104 gcnew constraint, 300–301 converting strings generic types using, 296–304 with other data types, 85–86 guaranteeing existence of an operator, 316 copy constructors interface constraints, 296–297 parameter to, 55 multiple constraints, 303–304 reference types, 63, 121 reference type constraints, 303 using tracking references with, 55 value type constraints, 301–303 value types, 121 constructed types, 289 384 ■INDEX

Copy method, Array class, 102, 104 debugging copying arrays, 104 displaying Object as string, 45 copying strings, 76 declaration specifier for calling CopyTo method, Array class, 104 conventions, 348 cout, using with String class, 91 clr:pure mode, 31 CreateDomain method, AppDomain compilation modes available for, 363 class, 284 compiling native class into DLL, 325 CreateInstance method double thunking, 348 Activator class, 280 deep copy, strings, 76 AppDomain class, 284 Scrabble game, 127 Array class, 104 default indexed properties cross-language interoperability, 319–322 arrays in classes, 108 CLS compliant language features, 321 backing property with collection, 180 consuming wrapped global function defining/using, 178 in C#, 320 delegate keyword, 356 creating interface in C++, 320 delegates, 23–26, 184–190 description, 317 assigning to static method, 25 pure mode and safe mode, 319 asynchronous delegates, 188–190 using interface in Visual Basic, 320 creating delegate type, 23 wrapping global function, 319 customizing add/remove/raise event CRT (C Runtime) library methods, 194 compiling with, 90 declaring, 25 compilation modes available for, 362 declaring events and event handlers, 191 secure variants of, 91 events and, 23, 26 using native libraries without P/Invoke, 329 up and firing events, 26 CRT file pointer, 165 invocation list of functions, 184 C-style casts, 208, 209, 366 MulticastDelegate class, 184 CTS (common type system), 3–5 overloaded functions, 184 aggregate types, 12–14 referencing nonstatic member function, 25 primitive types, 4, 11–12 return values, 185 Current property, CardEnumerator class, 249 syntax, 368 Current property, IEnumerator, 79 unrelated to System::EventHandler, 196 ■D using delegate with property accessor, 176 walking through invocation list, 186, 187 data marshaling see marshaling delete command data storage class destruction and cleanup, 161 reference and value types compared, 118 controlling when object goes out of data types see types scope, 49 not calling delete on managed objects, 52 ■INDEX 385 dereferencing handles, 54, 56 DllImport attribute derived classes calling Win32 function in C++/CLI, 322 finalizers, 232 CallingConvention property, 324, 326 order of initialization, 227, 228 CharSet parameter, 323 using virtual functions in constructor, EntryPoint property, 323, 324 229, 230 doc compiler option, 359 derived functions, 228 documentation, XML, 359–362 design patterns domains, application, 283–284 asynchronous delegates, 188 double thunking, 348 pattern for using destructor and Double type, 11 finalizer, 163 DrawTile method, Scrabble game, 134 destructors dynamic type, 280 auto_gcroot template, 160 dynamic_cast, 208, 209 calling, 231 http://superindex.apress.com at it faster Find C++/CLI alternative to C++, 18 calls between destructors and finalizers, 168 casting in inheritance hierarchies, 233 class destruction and cleanup, 160–161 syntax, 365 handling managed and unmanaged dynamically loaded types resources, 167 interfaces and, 255–257 inheritance, 231 reference and value types compared, 118 ■E static destructors, 120 elements using destructor and finalizer, 162, 163 ConvertAll method, Array class, 104 using native objects in managed types, 159 deletion and insertion in arrays, 108 using this pointer, 153 FindLast method, Array class, 104 virtual destructors, 231 GetValue method, Array class, 105 developer platforms IndexOf method, Array class, 105 .NET Developer Platform, 29–41 SetValue method, Array class, 105 dictionaries, 308–309 encoding, specifying for output file, 87 Dictionary class, 308 EndInvoke method, Delegate class, 188 multiple constraints, 304 entry points directives, using, 37–38 main method, 8, 9, 364 Dispose method managed entry point, 347–348 class destruction and cleanup, 161 native entry point, 347–348 controlling when object goes out of unnecessary context switches, 348 scope, 50 EntryPoint property, DllImport attribute, traversing linked list with for each, 295 323, 324 DivideByZeroException, 260 enum class, 17–18, 111 DLL, 6 Flags attribute, 113–114 compiling native class into, 324 formatting with, 115 generating, 39 Format method, 115 invoking native functions in safe mode, 322 safe_cast, 18 386 ■INDEX

Scrabble game, 128 description, 127 underlying type, 112 event receivers and senders, 199–201 enum class keyword, 357, 365 hooking up and firing, 26 enum struct keyword, 357 interfaces with properties and, 240 enumerated types, 110–116 introduction, 26 conversions, 112 locking add and remove accessors, 193 enumeration values, 114–116 locking raise method, 193 enumerators providing custom event data, 201 changing collection, 249 reserved names, 203 GetEnumerator method, 104 syntax, 369 IEnumerable interface, 248–255 type, 26 IEnumerator interface, 248–255 using EventArgs Class, 201 equality, arrays, 106–107 Events class, 191 Equals method, Array class, 104, 106 EventSender class, 200 Equals method, String class, 76 example tag, XML documentation, 359 error handling, files, 88 except structured exceptions, 348–351 Error property, Console class, 87 Exception class errors creating custom exceptions, 262–263 exceptions and errors from native code, InnerException property, 261 269 Message property, 260 GC hole, 340 Source property, 260 interop with Win32 error codes, 351–352 StackTrace property, 260 swallowing, 269 table of exceptions, 260 event handlers, 26 using properties of, 261 see also events exception handling accessor methods, 191, 193 C++/CLI and classic C++ compared, 259 customizing methods for, 191 coexistent C++ and CLR exception event keyword, 191, 356 handling, 353 EventArgs class, 201 guidelines, 268 EventHandler class, 199 handling which exceptions, 269 EventHandler type, 191, 192, 196 exception tag, XML documentation, 359 EventProcessor type, 196 exceptions, 259–269 EventReceiver class, 200 ArgumentException, 309 events, 191–203 cascading, 261 see also event handlers CLS compliant alternative, 321 C++/CLI events introduced, 191 compilation modes available for, 363 declaring events, 26 creating custom exceptions, 262–263 declaring events and event handlers, 192 exception specifications feature, 268 delegates and, 23, 26 exceptions and errors from native code, 269 ■INDEX 387

exceptions in constructors, 265–266 File class finally block, 263–264 opening StreamWriter, 87 interop with C++ exceptions, 352–354 finalizers, 161–170 interop with COM HRESULTs, 354 calling, 232 interop with structured exceptions, calls between destructors and, 168 348–351 closing stream in, 168 InvalidCastException, 210 handling managed and unmanaged KeyNotFoundException, 309 resources, 167 pitfalls of finalizers, 170 inheritance, 232–233 properties, 260–262 pattern for using destructor and, 163 rethrowing in catch block, 269 pitfalls of, 168–170 syntax, 371 syntax, 367 table of, 260 using destructor and, 162, 163 Find it faster at http://superindex.apress.com at it faster Find throwing, 259 using native objects in managed types, 159 throwing in constructors, 265 using this pointer, 153 throwing objects, not exceptions, 266–269 finally blocks, 263–264 warning, 268 cleanup code, 269 unhandled exceptions, 261 finally keyword, 263, 356 wrapping nonexception object, 267 Find method, Array class, 104 ExecuteAssembly method, AppDomain FindAll method, Array class, 104 class, 284 FindIndex method, Array class, 104 Exists method, Array class, 104 FindLast method, Array class, 104 Exit event, 191, 194, 195, 197 FindLastIndex method, Array class, 104 explicit delete, 49 FindWinner method, Scrabble game, 137 explicit interface implementation, 371 Flags attribute, Enum class, 113–114 explicit keyword, 206–208 enum formatting with Flags attribute, 115 compilation modes available for, 363 floating-point control, 362 exponentiation operator, 203 for each keyword, 357 expressions, how compilers understand, 56 for each statement, 10, 364 extensions generic collection classes, 290 enabling standard extensions for IEnumerable interface, 248, 249 C++/CLI, 3 iterating over dictionary collection, 309 ■F iterating with, 307 f() function signatures, 70 traversing linked list with for each, 291 fields using for each to traverse arrays, 98 const fields, 121 ForEach method, Array class, 104 initonly fields, 124–125 format characters, 114, 115 literal fields, 121–124 properties and, 173 388 ■INDEX

Format method parameterized functions, 285 Enum class, 115 passing value/reference types to, 62 String class, 81, 82 polymorphic functions, 235 Scrabble game, 129 sealed modifier, 221 formatting strings, 81–82 special member functions and numeric string formatting, 82–84 inheritance, 225–233 FreeHGlobal method, Marshal class, 347 thunk, 347 friend assemblies, 39 virtual functions in constructor, 228–230 friend functions and classes, 203 functions, list of global friend functions, 205 see also methods, list of friend operators, 205 MessageBox, 322, 323, 329, 330, 331 FU (Force Using) compiler option, 38 pow, 203 fully qualified names, 6 printf, 90, 91 FUNCSIG macro, 325 printf_s, 91 function pointers, 184 swap_value, 65 functions Win32, 323 see also methods ■G adding to/removing from invocation gameBoard array, Scrabble game, 131 list, 184 garbage collection, 1–2 asynchronous delegates, 188 auto_gcroot template, 159 calling with tracking reference, 54 class destruction and cleanup, 161 changing value type in, 65 creating managed objects with gcnew, 2 checking function completion, 189 finalizers, 161–170 declaring any function abstract, 219 GC hole error, 340 declaring generic functions, 286 gcroot template, 159 delegates and, 184 managed heap, 2 derived functions, 228 pitfalls of finalizers, 168 explicitly specifying function to roots, 159 override, 217 GC class friend functions, 203, 205 Collect method, 163 function signatures, 70 GC hole error, 340 function taking handle type, 52 gc-lvalues, 56–58 generic functions, 286–288 gcnew constraint, 300–301 global functions, 319 gcnew keyword, 355 implementing inherited functions separately, 243 creating managed objects with, 2 instance functions, 220 initializing arrays with, 93 managed functions, 362 initializing arrays without, 94 native functions, 327, 362 syntax, 364 overloaded functions, 184 using in generic type, 300 using managed array type, 15 ■INDEX 389 gcroot template generics, 285–308 auto_gcroot compared, 342 see also generic types containing handle in native type, 342 declaring generic function, 286 syntax, 374 declaring multiple generic using managed types in native classes, 159 parameters, 286 gc-rvalues, 56–58 managed templates compared, 309, 314 generic classes reasons for generics in C++/CLI, 285 ArrayList class, 305–308 templates compared, 285 assuming existence of an operator, 315 using a generic list, 110 Dictionary class, 308 using collection class interfaces, 305 generic/nongeneric container classes, 304 using generic list for strings, 298 KeyValuePair class, 309 get method see accessor (get and set) methods of properties syntax, 372 GetAttributes method, Type class, 280 http://superindex.apress.com at it faster Find using reference or value types, 70 GetCustomAttribute method, Attribute generic collection classes, 290–295 class, 279 generic functions, 286–288, 373 GetEnumerator method generic interfaces, 313, 314 Array class, 104 generic keyword, 285, 355 IEnumerable interface, 248 generic types, 27–28, 288–290 traversing linked list with for each, 295 see also generics GetHashCode method, Array class, 104 class constraints, 297–298 GetInvocationList method, Delegate compiler restrictions on, 289 class, 187 constructed types, 289 GetLastError method, Marshal class, 351 defining generic List class, 27 GetLastWin32Error method, Marshal gcnew constraint, 300–301 class, 351 interface constraints, 296–297 GetLength method, Array class, 104 iterating through generic collection, 28 GetLongLength method, Array class, 104 multiple constraints, 303–304 GetLowerBound method, Array class, 105 parameters, 285–286 GetMembers method, Type class, 280 reference class using generic List as GetMethods method, Type class, 280 property, 27 GetPlayStartPosition method, Scrabble reference type constraints, 303 game, 141 reference/value types as type parameters, GetPlayType method, Scrabble game, 140 298–300 GetTilesForPlay method, Scrabble game, 141 treating unknown type as handle, 299 GetType method, Array class, 105 type safety, 289 GetType method, Type class, 280 using constraints, 296–304 GetTypes method, Assembly class, 279 value type constraints, 301–303 GetUpperBound method, Array class, 105 390 ■INDEX

GetValue method, Array class, 105 syntax, 363 GetWorkingTiles method, Scrabble game, 145 temporary handles, 66–68 global functions, 319 tracking references and, 53 CLS compliant alternative, 321 treating object on heap as if on stack, 51 consuming wrapped global function treating unknown generic type as, 299 in C#, 320 using command line arguments, 10 wrapping, 319 using handle to value type, 68 GlobalFree method, 347 using managed array type, 15 ■H using managed object in native class, 342 handles using two handle symbols, 10 abstract classes, 220 “has-a” relationship, 21 accessing reference types, 4 hash code array address, 93 GetHashCode method, Array class, 104 array of handles in Scrabble game, 127 heap auto_handle template, 58–60 creating native objects with new or malloc, 2 C++/CLI exceptions, 259 declaring variables on stack or on heap, C++/CLI stack semantics, 68 47–52 caret (^) character, 7 heap compaction, 2 const_cast, 209 heap object lifecycle, 48 containing handle in native type, 342 managed heap, 2 creating handle to object using %, 66 native heap, 2 dereferencing handles, 54 treating object on heap as if on stack, 50 function taking handle type, 52 “Hello World” program, 5–10 gc-lvalues and gc-rvalues, 56 helper classes, Scrabble game, 127 gcroot and auto_gcroot compared, 343 HRESULT error codes generic types, 27 exceptions and errors from native code, 269 holding values of native OS handles, 323 interop with COM HRESULTs, 354 introduction, 1, 2 HWnd class main method arguments, 9 wrapper classes for unmanaged method requiring handle, 52 resources, 163 object semantics for reference types, 43 ■ passing handle by reference using ^% I indirection, 54 IAddition interface, 316 passing object by reference in C++/CLI, 62 IAsyncResult interface, 189 passing value types as handles, 68–70 IComparable interface, 246–248 pitfalls treating object on heap as if on CompareTo method, 246 stack, 52 comparing strings, 80, 81 pointers compared, 2 sorting array, 105 reference types, 5 using generic IComparable, 246 return values, 73 ■INDEX 391

IConvertible interface, 85 in keyword, 356 identifiers, keywords as, 357 In property, Console class, 87 IDisposable interface include directive, 6 class destruction and cleanup, 161 include tag, XML documentation, 359 Dispose method, 295 indexed properties, 22, 177–184 IEnumerable interface, 248–255 backing property with collection, 180 changing collection, 249 Chars indexed property, 76 enumerating playing cards, 249 default indexed property, 108, 178 for each statement, 248, 249 using multiple indexes, 182 generic collection classes, 290 indexes generic form, 255 code substitutions, 81 GetEnumerator method, 248 FindIndex method, 104 String class implementing, 79 FindLastIndex method, 104 Find it faster at http://superindex.apress.com at it faster Find traversing linked list with for each, 295 GetLowerBound method, 105 IEnumerator interface, 248–255 GetUpperBound method, 105 Current property, 79 iterating with, 307 enumerating playing cards, 249 LastIndexOf method, 105 generic collection classes, 290 IndexOf method, Array class, 105 IJW (it just works), 317 IndexOutOfRangeException, 260 IKey interface, 304 going past the end of arrays, 99 IL (Intermediate Language) indirection CIL, 3 passing handle by reference using ^%, 54 architecture dependence and 64-bit indirection operator, 108 programming, 32 inheritance, 211–234 compilation modes available for, 362 abstract classes, 219–220 introduction, 319 interfaces compared, 220 ILDasm (Intermediate Language attributes, 271 Disassembler), 34–37 C++/CLI and classic C++, 211, 212 IList generic wrapper class constructors, 226–228 AsReadOnly method, Array class, 104 order of initialization, 227 IList interface virtual functions in, 228–230 Array class, 103 CTS (common type system), 4 iterating with for each and with index, 308 destructors, 231 trapping invalid cast exception, 307 finalizers, 232–233 implements keyword, 235 implementing inherited functions import directive separately, 243 COM interop, 328 interface classes, 19 COM libraries, 37 interface inheritance, 238 compilation modes available for, 362 multiple inheritance, 211 pure mode, 31 392 ■INDEX

primitive types, 45 Console class, 86–87 private and protected inheritance, 212 reading and writing files, 87–89 reference and value types compared, 118 reading and writing strings, 89–90 reference types, 4 StreamReader class, 87–89 sealed classes, 220–222 StreamWriter class, 87–89 special member functions and, 225–233 String class, 90–92 value classes, 117 StringReader class, 89–90 value types, 4, 212 StringWriter class, 89–90 virtual properties, 222–225 instance functions, 220 inheritance hierarchies Int16/Int32/Int64 types, 11 casting in, 233–234 integers cross-language interop, 317 boxing an integer type, 45 name collisions in, 212–219 unboxing Object to integer, 46 new keyword, 214–215 interface class keyword, 357, 365 override keyword, 215–219 interface class type, 12 Inherited property, 279 interface classes, 19–20 initialization interface handles, 235 constructor order of, 227 dynamically loaded types, 255 initializing attribute with properties, 278 interface name collisions, 242 initializing static initonly field, 125 interface implementation, 371 managed types, 118 interface inheritance model, 241 static constructors, 119 interface keyword, 236 static initialization, 119 interface struct keyword, 357 TypeInitializationException, 260 interfaces, 235–257 Initialize method, Array class, 105 abstract classes compared, 220, 235–236 initializing arrays, 93–95 access control, 236 initializing part of arrays, 96 assembly using template type in public initonly fields, 124–125 interface, 311 initializing static initonly field, 125 CLS compliant alternative, 321 new types of constant values, 118 creating interface in C++, 320 Scrabble game, 131 declaring, 236–237 syntax, 367 declaring and implementing, 236 initonly keyword, 356 declaring generic interface, 313 inline assemblies, pure mode, 31 declaring generic interface for template, 313 InnerException property, Exception class, 261 defining and implementing, 19 InnerObject property, 309 dynamically loaded types and, 255–257 input/output, 86–92 explicitly specifying implicit base classes, 237 basic I/O functions, 86 ■INDEX 393

implementing inherited functions internal keyword, 356 separately, 243 internal modifier, 156, 157 implementing multiple interfaces, 236 interoperability (interop), 317–354 implements keyword, 235 C++/CLI, 317 interface constraints, 296–297 choice of compilation mode, 322 interface inheritance, 238 COM interop, 318, 328–329 interfaces and access control, 244 cross-language interop, 317, 319–322 interfaces implementing other interfaces, interior pointers, 339–340 237–239 interop with C++ exceptions, 352–354 interfaces with properties and events, 240 interop with COM HRESULTs, 354 interfaces with static fields and interop with other .NET languages, methods, 245 319–322 literals in interfaces, 246 interop with structured exceptions, members, 236 348–351 http://superindex.apress.com at it faster Find methods implementing interface interop with Win32 error codes, 351–352 methods, 236 IntPtr struct, 323 multiple inheritance, 235 invoking native functions in safe of interfaces, 211 mode, 322 name collisions, 240–243 managed entry point, 347–348 disambiguating, 241, 242 managed templates and generics implementing inherited functions compared, 316 separately, 243 Marshal class, 328 object types, 235 native C++ code, 317 reference and value types compared, 118 native entry point, 347–348 using collection class interfaces, 305 Out attribute, 272 using generic interface instead of pinning pointers (pin_ptr), 340–341 template, 314 P/Invoke, 317 using in Visual Basic, 320 pure/safe modes, 272 using new to implement interface recompiling native library as managed method, 238 code, 332–339 using private method to implement, 244 types of interop, 317–319 interior pointers, 155, 339–340, 373 using C++ source code, 318 assigning value to, 339 using managed object in native class, compilation modes available for, 363 342–343 converting to pinned pointer, 156 using native libraries with P/Invoke, navigating arrays using, 99 322–328 using interior pointers to traverse using native libraries without P/Invoke, arrays, 99 329–332 Intermediate Language see IL using native object in managed type, internal access control specifier, 156 343–347 394 ■INDEX

IntPtr struct for each, 357 calling Win32 function in C++/CLI, 323 gcnew, 355 ToPointer method, 347 generic, 285, 355 intrinsics, pure mode, 31 implements, 235 InvalidCastException, 208, 210, 260 in, 356 casting in inheritance hierarchies, 233 initonly, 356 generic/nongeneric container classes, 304 interface, 236 trapping invalid cast exception, 306 interface class, 357 InvalidOperationException, 249 interface struct, 357 invariant, 7 internal, 356 invocation list, 184, 186 literal, 356 Invoke method, delegates, 184 new, 214–215 InvokeMember method, Type class, 280 nullptr, 355 IOException type, 88 override, 215–219, 356 iostreams library, 211 private, 156 “is-a” relationship, 235 property, 356 isotope number, 12 public, 156 isotopes, 181 ref, 7 iterators, traversing arrays, 97 ref class, 309, 357 ■J ref struct, 357 sealed, 356 Java static, 122 interface inheritance model, 241 struct, 357 JIT (just-in-time) compiler, 3 template, 309 ■K typename, 285 KeyNotFoundException, 309 value class, 357 KeyValuePair class, 309 value struct, 357 keywords, 355, 356, 357 virtual, 222 whitespaced keywords, 7, 357 where, 356 keywords, list of ■ abstract, 219, 356 L LastIndexOf method, Array class, 105 based, 363 late binding class, 285 reflection dealing with unidentified delegate, 356 types, 282 enum class, 357 LD compiler option enum struct, 357 generating DLL, 39 event, 356 reference classes, 14 explicit, 206 finally, 263, 356 ■INDEX 395 length, arrays defining static constants and, 123 GetLength method, 104 initializing literals, 121 GetLongLength method, 104 new types of constant values, 118 LongLength property, 103 Scrabble game, 130, 132 Length property, Array class, 95, 103 static keyword, 122 libraries syntax, 367 abstract classes and interfaces compared, literal keyword, 356 220, 236 literal values clr:pure mode, 31 literals in interfaces, 246 mixing native and managed libraries, 92 string literals, 76 recompiling native library as managed treating as objects, 46 code, 332–339 LN compiler option, 33 using native libraries with P/Invoke, Load method, AppDomain class, 284 322–328 http://superindex.apress.com at it faster Find LoadFrom method, Assembly class, 279 using native libraries without P/Invoke, 329–332 lock class, 374 link.exe see linkers lock object linked lists customizing event methods, 194 traversing with for each, 291 description, 196 linkers using delegate unrelated to EventHandler, 197 assembly linker, 40 lock template, msclr\lock.h, 193 CLR programming, 40 LongLength property, Array class, 103 command-line options, 40 looping through strings, 78 link.exe, 40 LPCWSTR parameter, 331 traditional linker, 40 lvalues using native libraries without P/Invoke, 330 chaining expressions involving List class properties, 174 defining generic List class, 27 gc-lvalues and, 56 iterating with for each and with index, 307 how compilers understand list tag, XML documentation, 359 expressions, 56 ListEnumerator class ■M traversing linked list with for each, 295 main method, 8, 9, 364 lists malloc statement, 2 Scrabble game, 127 managed using generic list for strings, 298 use of term in this book, 2 literal fields, 121–124 managed array type, 92–110 accessing, 122 accessing elements, 93 compile-time constants, 123 array equality, 106–107 compiling static constants and, 123 ArrayList class, 108–110 declaring, 121 396 ■INDEX

arrays as parameters, 101–102 managed functions/headers arrays in classes, 108 compilation modes available for, 362 copying arrays, 102–103 managed heap, 2 declaring, 92 gc-lvalues and gc-rvalues, 56 initializing, 93–95 native and managed arrays compared, introduction, 9 100, 101 managed array class members, 103–106 managed objects native arrays compared, 100–101 not calling delete on, 52 navigating arrays, 97–100 pitfalls of finalizers, 168, 170 parameter arrays, 107–108 using in native class, 342–343 syntax, 364 managed resources, handling, 164 using, 14 managed string type using as function parameter, 102 calling Win32 function in C++/CLI, 323 managed base classes, 228, 229 managed templates, 309–316 managed C++ assembly using in public interface, 311 use of term in this book, 2 assuming existence of operator, 315 managed classes constraint guaranteeing existence of operator, 316 const fields, 121 declaring generic interface for, 313 copy constructors, 55 generics compared, 309, 314 literal fields, 121–124 passing class types over assembly multiple inheritance, 211 boundary, 311 order of initialization, 227 reasons for using, 314 using Win32 functions in managed ref class template, 310 class, 331 syntax, 372 managed code using generic interface instead of, 314 calling convention for managed functions, 347 using template from another assembly, 314 context switch, 327 using template in another assembly, 312 marshaling types between native code and, 327 using template with different types, 310 recompiling native library as, 332–339 managed types, 12 using #pragma managed/unmanaged, 338 address-of operator for, 52 using reference types with stack compilation modes available for, 362 semantics, 47,–2 constructors, 118 managed derived classes, 228, 230 conversion operators, 206–210 managed entry point, 347–348 implications of unified type system, 44–45 native function, 327 initialization, 118 managed extensions syntax, Visual introduction, 1 C++ 2005, 32 managed templates, 311 ■INDEX 397

reference types, 4 MessageBox function, 322, 323, 329, 330, 331 reference types or value types, 4 MessageBoxClass use of term in this book, 4 creating native MessageBoxClass, 332 using managed array type, 15 using wrapper from C# assembly, 337 using in native classes, 159–160 wrapping, 334, 335 using native object in, 157–159, 343–347 messages value types, 4 Obsolete attribute, 272 manifest, assembly, 33–37 metadata Marshal class, 328 accessing programmatically, 279 FreeHGlobal method, 347 assemblies, 33 GetLastError method, 351 description, 270 GetLastWin32Error method, 351 viewing with ILDasm.exe, 34–37 StringToHGlobalUni method, 347 methods Find it faster at http://superindex.apress.com at it faster Find using native objects in managed types, 158 see also functions MarshalAs attribute, 328 abstract classes and interfaces compared, marshaling 220, 236 character, string, and structure types, 327 abstract methods, 370 context switch, 327 accessor (get/set) methods of events, 191, 193, 203 data marshaling, 327–328 accessor (add/remove) methods of description, 159, 318 properties, 173–177 marshaling types between native and const correctness, 126 managed code, 327 interface inheritance, 238 primitive types, 327 interface name collisions, 240 using cout with String class, 91 interfaces with static fields and, 245 members methods implementing interface special member functions and methods, 236 inheritance, 225–233 methods requiring handles, 52 value type with, 8 private methods, 244 value types defining special member functions, 15 sealed methods, 370 memory sealed modifier, 220 creating native objects with new or static methods, 245, 280 malloc, 2 using new to implement interface managed/native heaps, 2 method, 238 memory layout of Scrabble game virtual methods, 215–219, 236, 322 features, 128 methods, list of OutOfMemoryException, 260 see also functions, list of Message property, Exception class, 260 add, event handlers, 191, 193 creating custom exceptions, 262 AsReadOnly, Array class, 104 error handling for files, 88 BeginInvoke, Delegate class, 188, 189 unhandled exceptions, 261 BinarySearch, Array class, 104, 105 398 ■INDEX

Clear, Array class, 104 GetLastError, Marshal class, 351 Clone, Array class, 104 GetLastWin32Error, Marshal class, 351 Collect, GC class, 163, 170 GetLength, Array class, 104 Combine, Delegate class, 186 GetLongLength, Array class, 104 Compare, String class, 80, 81 GetLowerBound, Array class, 105 CompareOrdinal, String class, 81 GetMembers, Type class, 280 CompareTo, String class, 80, 81 Gets, Type class, 280 CompareTo, IComparable interface, 246 GetType, Array class, 105 Concat, String class, 76 GetType, Type class, 280 ConstrainedCopy, Array class, 104 GetTypes, Assembly class, 279 ConvertAll, Array class, 104 GetUpperBound, Array class, 105 Copy, Array class, 102, 104 GetValue, Array class, 105 CopyTo, Array class, 104 GlobalFree, 347 CreateDomain, AppDomain class, 284 IndexOf, Array class, 105 CreateInstance, Activator class, 280 Initialize, Array class, 105 CreateInstance, AppDomain class, 284 Invoke, 184 CreateInstance, Array class, 104 InvokeMember, Type class, 280 Dispose, 50 LastIndexOf, Array class, 105 EndInvoke, Delegate class, 188 Load, AppDomain class, 284 Equals, Array class, 104, 106 LoadFrom, Assembly class, 279 Equals, String class, 76 main, 8, 9, 364 ExecuteAssembly, AppDomain class, 284 raise, events, 191 Exists, Array class, 104 RaiseExitEvent/RaiseStartEvent s, 191, Find, Array class, 104 195, 198 FindAll, Array class, 104 Read, StreamReader class, 87 FindIndex, Array class, 104 ReadLine, StreamReader class, 87 FindLast, Array class, 104 ReadLine, Console class, 87 FindLastIndex, Array class, 104 Remove, 186 ForEach, Array class, 104 remove, event handlers, 191, 193 Format, Enum class, 115 Resize, Array class, 105 Format, String class, 81, 82 Reverse, Array class, 105 FreeHGlobal, Marshal class, 347 set, properties, 22, 173–177, 203 get, properties, 22, 173–177, 203 SetValue, Array class, 105 GetAttributes, Type class, 280 Sort, Array class, 105 GetCustomAttribute, Attribute class, 279 StringToHGlobalUni, Marshal class, 347 GetEnumerator, Array class, 104 ToCharArray, String class, 77, 78 GetEnumerator, IEnumerable interface, 248 ToPointer, IntPtr struct, 347 GetHashCode, Array class, 104 ToString, Array class, 105 GetInvocationList, Delegate class, 187 ToString, String class, 80 ■INDEX 399

ToXyz methods, 85 MSIL see IL TrueForAll, Array class, 105 multicast delegates, 184 UseData, 170 customizing add/remove/raise event Write, Console class, 86 methods, 194 Write, StreamWriter class, 87 MulticastDelegate class, 184 WriteLine, Console class, 81, 86 multifile assemblies, 41 WriteLine, StreamWriter class, 87 multiple inheritance, 211 MFC (Microsoft Foundation Classes) interfaces, 235 clr:pure mode, 31 ■N compilation modes available for, 362 name collisions memory map, 191 inheritance hierarchies, 212–219 mixed mode, 31 interfaces, 240–243 see also pure mode; safe mode

native http://superindex.apress.com at it faster Find architecture dependence and 64-bit use of term in this book, 2 programming, 32 native arrays, 100–101 detecting CLR compilation, 358 native base classes, 227, 229 features available for, 362 native classes IJW (it just works), 317 compiling into DLL, 324 interoperability, 317 destructors and inheritance, 231 using C++ source code, 318 order of initialization, 227 reference classes, 14 using managed object in, 342–343 using native libraries without P/Invoke, using managed types in, 159–160 329, 330 native code Visual C++ 2005, 3, 31 CLS compliant alternative, 321 mixed types not supported, 14 exceptions and errors from, 269 modifiers interoperability, 317 abstract modifier, 220 invoking in safe mode, 322 accessibility modifiers, 37, 156, 157 marshaling types between managed code as_friend modifier, 39 and, 327 internal modifier, 156, 157 P/Invoke knowing calling convention of override modifier, 222 target function, 324 private modifier, 157 pure mode, 31 protected modifier, 157 using #pragma managed/unmanaged, 338 public modifier, 157 wrapping native type thrown from, 352 sealed modifier, 220 native derived classes, 227, 229 module attributes, 276–277 native entry points, 347–348 modules, 33 native exports, pure mode, 31 msclr namespace, 159 native functions, 327, 362 lock template, 193 native headers, 362 mscorlib.dll, 37, 38 400 ■INDEX

native heap nullptr keyword, 355, 364 creating native objects with new, 2 nullptr value native libraries casting in inheritance hierarchies, 233 creating native MessageBoxClass, 332 dynamic_cast, 209 recompiling as managed code, 332–339 object semantics for reference types, 43 using without P/Invoke, 329–332 NullReferenceException, 260 native mode, 32, 322 object semantics for reference types, 43 features available for, 362 numeric string formatting, 82–84 native objects/types, 1 ■O compilation modes available for, 362 obfuscated names, 325, 327 containing handle in native type, 342 Object type creating with new or malloc, 2 debugging tool, 45 mixed types not supported, 14 displaying Object as string, 45 using in managed types, 157–159, 343–347 implications of unified type system, 44 native pointers, encapsulating, 344 public methods, 44 native resources see unmanaged resources unboxing Object to integer, 46 navigating arrays, 97–100 unified type system, 3 interior pointers, 99 value type converted to, 46 using for each to traverse arrays, 98 object types using interior pointers to traverse interfaces, 235 arrays, 99 return values, 70 using iterators to traverse arrays, 97 objects NDP (.NET Developer Platform), 29–41 abstract classes and interfaces targeting with Visual C++ 2005, 29 compared, 235 .NET Framework, 5 collections owning and deleting, 302 compilation modes available for, 362 native and managed arrays compared, 101 container types, 304 orphaned objects, 43 .NET languages querying object attributes at runtime, 279 interoperating with other, 319–322 throwing objects, not exceptions, 266–269 .NET module, 33 warning, 268 new keyword, 214–215 treating object on heap as if on stack, 50 sealed classes, 221 wrapping nonexception object, 267 using on virtual functions, 214–215 Obsolete attribute, 271–272 using to implement interface method, 238 oldSyntax option see managed using to override overriding, 214 extensions syntax new statement, 2 OnExit event handler, 195, 198 NOASSEMBLY linker option, 33 OnStart event handler, 195, 198 NonSerialized attribute, 273 operator overloading, 203–210 NotFiniteNumberException, 260 CLS compliant alternative, 322 ■INDEX 401 operators overriding % operator, 52–53 overriding basic property, 222 & (address-of) operator, 52, 60 using new keyword to override * operator, 54 overriding, 214 + operator, 79, 80, 205 ■P += operator, 22, 184, 194 para tag, XML documentation, 360 -= operator, 22, 184, 185 param tag, XML documentation, 360 addition operator, 79, 80 parameter arrays, 107–108 address-of operator (&), 52 parameterization, 309 assignment operator (=), 43 parameterized function, 285 conversion operators, 206–210 parameterized types, 12, 27 description, 127 templates and generics compared, 285 exponentiation operator, 203

using in assembly public classes and http://superindex.apress.com at it faster Find friend operators, 205 methods, 312 indirection operator, 108 parameters precedence and evaluation, 203 arrays as, 101–102 scope operator (::), 38 attribute parameters, 271 static operators, 203–206 passing by reference in C++, 62 string operators, 79,–0 passing by value and by reference tracking reference operator (%), 66 in C++, 60 ordinal numbers passing object by reference in C++/CLI, 62 CompareOrdinal method, 81 passing, 60–70 orphaned objects, 43 table of function signatures, 70 Out attribute, 272–273 temporary handles, 66–68 Out property, Console class, 87 passing pointer by reference in C++, 62 OutOfMemoryException, 260, 265, 268 passing reference types by value, 63–64 output file, specifying encoding of, 87 passing value types as handles, 68–70 OverflowException, 260 passing value types by reference, 65–66 overloaded functions, 184 specifying out-only parameter, 272 overloading, operators, 203–210 using generic array as, 287 override keyword, 215–219 paramref tag, XML documentation, 360 description, 356 Pass method, Scrabble game, 138 explicitly specifying function to passing parameters, 60–70 override, 217 passing by reference in C++, 62 sealed classes, 221 passing by value and by reference using on virtual methods, 215–219 in C++, 60 using to implement virtual function, 216 passing handle by reference using ^% indirection, 54 override modifier, 222 passing object by reference in C++/CLI, 62 402 ■INDEX

passing pointer by reference in C++, 62 platforms passing reference types by value, 63–64 .NET Developer Platform, 29–41 passing value types as handles, 68–70 Play method, Scrabble game, 136 passing value types by reference, 65–66 Player struct, Scrabble game, 130 table of function signatures, 70 PlayerMove method, Scrabble game, 146 temporary handles, 66–68 players array, Scrabble game, 131 patterns see design patterns playing cards, enumerating, 249 performance PlayType class, Scrabble game, 129 exception specifications feature, 268 point_values array, Scrabble game, 129 generic collection classes, 290 pointers implicit boxing and unboxing, 46 CLS compliant alternative, 321 permission tag, XML documentation, 360 const_cast, 209 pinning pointers (pin_ptr), 155, 340–341 dangerous C function, 61 converting interior pointer to, 156 dereferencing, 54 syntax, 373 dynamic_cast, 208 using cout with String class, 91 encapsulating native pointer, 344 using Win32 functions in managed class, handles compared, 2 331 holding values of native OS pointers, 323 P/Invoke, 317 interior pointers, 339–340 calling Win32 function in C++/CLI, 323 using to traverse arrays, 99 CallingConvention property, DllImport IntPtr struct, 323 attribute, 326 native and managed arrays compared, 101 CharSet parameter, 323 navigating arrays, 97 compilation modes available for, 362 navigating arrays using interior compiling native class into DLL, 324 pointers, 99 data marshaling, 327–328 passing by reference in C++, 62 holding values of native OS pinning pointers (pin_ptr), 91, 340–341 handles/pointers, 323 PtrToStringChars, 91 invoking native functions in safe safe mode, 330 mode, 322 static_cast, 208 knowing calling convention of target function, 324 this pointer, 153–156 using DllImport attribute EntryPoint using double pointer in C, 62 property, 324 using native objects in managed types, 159 using native libraries with, 322–328 polymorphic functions, 235 using native libraries without, 329–332 pow function, 203 placeholders pragma managed, 338 code substitutions, 81 pragma pack, 363 type parameter identifier, 286 pragma unmanaged, 338 platform invoke see P/Invoke compilation modes available for, 363 ■INDEX 403 precedence description, 127 operator overloading, 203 different ways of defining properties, 22 PreGame method, Scrabble game, 135 Exception class, 260–262 primitive types indexed properties, 22, 177–184 implicit boxing and unboxing, 45–47 initializing attribute with, 278 inheritance, 45 interfaces with properties and events, 240 introduction, 11–12 introduction, 21–22 marshaling, 327 overriding basic property, 222 synonyms for, 4 read-only properties, 22, 176 PrintBoard method, Scrabble game, 133 reference class using generic List as, 27 printf function reserved names, 203 compiling with CRT or safe mode, 90 scalar properties, 22 secure variants of CRT functions, 91 static properties, 177 Find it faster at http://superindex.apress.com at it faster Find printf_s function syntax, 368 secure variants of CRT functions, 91 trivial properties, 22 PrintPlayerTiles method, Scrabble game, 130 using delegate with property accessor, 176 PrintScores method, Scrabble game, 133 virtual properties, 222–225 private inheritance, 212 write-only properties, 183 private keyword, 156 properties, list of use of, 37 AllowMultiple, 279 private method AttributeTargets, 279 using to implement interface, 244 CallingConvention, 324, 326 private modifier, 157 Current, 79, 249 processor architecture dependence, 32 EntryPoint, 323, 324 program name, 10 Error, 87 properties, 173–177 In, 87 accessor (get and set) methods, 173 Inherited, 279 attribute properties, 279 InnerException, 261 chaining expressions, 174 InnerObject, 309 CLS compliant alternative, 321 Length, 95, 103 compound assignment operators, 22 LongLength, 103 computing property values, 174 Message, 260 declaring, 173 Out, 87 default indexed properties Rank, 103 arrays in classes, 108 Source, 260 backing property with collection, 180 StackTrace, 260 defining/using, 178 SyncRoot, 103 defining property accessors outside property keyword, 356 class, 176 protected access control specifiers, 156, 183 404 ■INDEX

protected modifiers, 157 Read method, StreamReader class, 87 public class, 39 ReadLine method, StreamReader class, 87 public keyword ReadLine method, Console class, 87 absence of, 19 read-only properties, 22, 176 protected public access control receivers, EventReceiver class, 200 specifier, 156 RecordPlay method, Scrabble game, 144 referencing assemblies, 39 ref class see reference classes use of, 37 ref class keyword, 309, 357 public modifier, 157 ref class template, 310 pure mode, 30–31 ref class type, 12 see also mixed mode; safe mode ref keyword, 7 architecture dependence and 64-bit ref struct keyword, 12, 357 programming, 32 reference classes features available for, 362 constructor inheritance, 226 interoperability, 272 introduction, 7, 14–15 cross-language interoperability, 319 managed reference classes, 1 using native objects in managed types, 159 mixed types not supported, 14 using native libraries without P/Invoke, ref class, 1, 14 329, 330 reference type constraints, 303 Visual C++ 2005, 30–31 Scrabble game, 127 ■R syntax, 365 radioactive decay program, 13 using generic List as property, 27 RAII (Resource Acquisition is using managed array type, 14 Initialization), 160 reference semantics, 4 raise method, events reference types customizing, 191, 193, 194, 195 accessing, 4 declaring events and event handlers, 193 as type parameters, 298–300 locking, 193 auto_handle template, 58 reserved names (raise_E) for events, 203 C++/CLI stack semantics, 66 using delegate unrelated to EventHandler, collection owning and deleting 197, 198 objects, 302 RaiseExitEvent/RaiseStartEvent methods const_cast, 209 customizing event methods, 195 copy constructors, 63, 121 declaring events and event handlers, 191 default constructor for, 118 using delegate unrelated to dereferencing handles, 54 EventHandler, 198 explicitly specifying implicit base Rank property, Array class, 103 classes, 237 rank, arrays, 93 handles, 5 native and managed arrays compared, Hello class, 6, 8 100, 101 inheritance, 4, 211 ■INDEX 405

interfaces, 211 reserved names, events and properties, 203 introduction, 4 Resize method, Array class, 105 object semantics for, 43 resources, assemblies and, 41 passing as reference, 4 return values passing object by reference in C++/CLI, 62 delegates, 185 passing reference types by value, 63–64 do's and don'ts, 70–73 passing to functions, 62 returns tag, XML documentation, 360 passing value types by reference, 69 Reverse method, Array class, 105 pitfalls of finalizers, 168 root, 159 reference type constraints, 303 runtime flexibility return values, 70 managed templates and generics table of function signatures, 70 compared, 316 this pointer, 153 RuntimeWrappedException object Find it faster at http://superindex.apress.com at it faster Find using reference types with stack throwing objects, not exceptions, 267 semantics, 47–52 rvalues value types compared, 117 chaining expressions involving referencing assemblies properties, 174 using directive, 37 gc-rvalues and, 56 reflection, 279–283 how compilers understand expressions, 56 compilation modes available for, 362 interfaces and dynamically loaded ■S types, 255 safe mode, 30 loading assembly and reflecting on see also mixed mode; pure mode types, 280 architecture dependence and 64-bit mode required, 279 programming, 32 reflecting on Late Binding, 282 features available for, 362 reflecting with Type methods, 280 interoperability, 272 reinterpret_cast, 209, 210 cross-language interoperability, 319 remarks tag, XML documentation, 360 invoking native functions in, 322 Remove method, 186 pointers, 330 remove method, event handlers printf function, 90 customizing, 193 reflecting with Type methods, 282 customizing methods, 191, 194 static_cast, 208 declaring events and event handlers, 193 structs, 330 reserved names (remove_E) for using native objects in managed types, 159 events, 203 using native libraries without P/Invoke, using delegate unrelated to 329, 330 EventHandler, 197 Visual C++ 2005, 30 ReplacePlayedTiles method, Scrabble game, 144 406 ■INDEX

safe_cast, 18, 209, 210, 365 ReplacePlayedTiles method, 144 casting in inheritance hierarchies, 233 ScrabbleGame class, 130 Enum class object conversions, 112 SpaceType class, 129 SafeHandle class, 163 spaceTypeColors array, 131 SByte type, 11 Tile struct, 129 scalar properties, 22 tilePopulation array, 131 scope UpdateScore method, 145 auto_handle template, 59 ScrabbleGame class, Scrabble game, 130 controlling when object goes out of, 49 sealed classes, 220–222, 370 heap objects, 48 sealed keyword, 356 value types, 4 sealed methods, 370 scope operator (::), 38 sealed modifier, 220, 221 Scrabble game, 127–153 searching AdjustPointTotals method, 137 BinarySearch method, 104 bag list, 131 security CalculateScore method, 148 signed assemblies, 41 Characters class, 128 see tag, XML documentation, 360 ConfirmPlay method, 144 seealso tag, XML documentation, 360 DrawTile method, 134 SEH (Structured Exception Handling), FindWinner method, 137 348–351 gameBoard array, 131 compilation modes available for, 363 GetPlayStartPosition method, 141 handling structured exceptions, 349 GetPlayType method, 140 senders GetTilesForPlay method, 141 EventSender class, 200 GetWorkingTiles method, 145 Serializable attribute, 273 main method, 152 serialization attributes, 273–275 memory layout of features, 128 set method see accessor (get and set) methods of properties Pass method, 138 set_terminate, 362 Play method, 136 SetValue method, Array class, 105 Player struct, 130 shallow copy, strings, 76 PlayerMove method, 146 Scrabble game, 127 players array, 131 signatures, functions, 70 PlayType class, 129 signed assemblies, 41 point_values array, 129 SIGTERM, 362 PreGame method, 135 Single type, 11 PrintBoard method, 133 Sort method, Array class, 105 PrintPlayerTiles method, 130 source code PrintScores method, 133 interoperability using, 318 RecordPlay method, 144 Source property, Exception class, 260 ■INDEX 407

SpaceType class, Scrabble game, 129 static methods spaceTypeColors array, Scrabble game, 131 interfaces with, 245 sparse array, 26 Type class, 280 stack static operators, 203–206, 369 C++/CLI stack semantics, 66 defining class to represent complex declaring variables on stack or on heap, numbers, 203 47–52 defining, 205 function taking handle type, 52 global friend functions replaced, 205 native and managed arrays compared, static properties, defining, 177 100, 101 static type, 280 stack object lifecycle, 48 static_cast, 208, 209, 365 treating object on heap as if on stack, 50 C++/CLI alternative to C++, 18 using reference types with stack stdcall calling convention

semantics, 47–52 http://superindex.apress.com at it faster Find P/Invoke knowing calling convention of stack semantics declaration, 367 target function, 324 StackTrace property, Exception class, 260 stdin/stdout/stderr streams rethrowing exceptions in catch block, 269 Console class properties exposed for, 87 unhandled exceptions, 261 StreamReader class, 87–89 Standard C++ library Read/ReadLine methods, 87 compilation modes available for, 362 streams using native libraries without P/Invoke, 329 closing in finalizer, 168 Start event StreamWriter class, 87–89 customizing event methods, 195 Write/WriteLine methods, 87 declaring events and event handlers, 191 String class, 90–92 using delegate unrelated to EventHandler, assigning string literals, 76 197 Chars indexed property, 76 static constants Compare method, 80 compiling, 123 CompareOrdinal method, 81 defining, 123 CompareTo method, 80, 81 literals in interfaces, 246 Concat method, 76 static constructors, 119–120, 367 constructor, 76 initonly fields, 124 description, 7, 75 this pointer, 153 Equals method, 76 static destructors, 120 Format method, 81, 82 static fields, interfaces with, 245 IConvertible interface, 85 static initialization, 119 IEnumerable interface, 79 initonly field, 125 secure variants of CRT functions, 91 static keyword, 122 ToCharArray method, 77 static members ToString function, 80 CLS compliant alternative, 321 using cout with, 91 408 ■INDEX

string literals, 7, 76 structured exceptions String type, 75 handling, 349 string type interop with, 348–351 pitfalls treating object on heap as if on structures stack, 51 classes compared, 9, 117 StringBuilder class, 84–85 summary tag, XML documentation, 360 description, 75 swallowing errors StringReader class, 89–90 handling exceptions only if you can, 269 strings, 75–86 swap_value function comparing, 76, 80–81 changing value type in function, 65 concatenating, 76, 79 SyncRoot property, Array class, 103 conversions with other data types, 85–86 synonyms, primitive types, 4 converting to character array, 78 syntax summary, 363–375 converting to primitive type, 85 System namespace copying, 76 Array class, 103 creating, 75 Console class, 86–87 editing, 80 defining primitive types, 4 enumeration values as, 114–116 String class, 90–92 format strings, 81 ■T formatting, 81–82 template class, 343 numeric string formatting, 82–84 template keyword, 309 looping through, 78 template types, 15 manipulation and editing, 84 passing over assembly boundary, 311 string operators, 79–80 templates String type, 75 CLS compliant alternative, 321 StringBuilder class, 84–85 declaring generic interface for, 313 ToString method, Array class, 105 description, 27 using generic list for, 298 generics compared, 285 StringToHGlobalUni method, Marshal class, 347 managed templates, 309–316 StringWriter class, 89–90 ref class template, 310 strong typing using generic interface instead of, 314 generic collection classes, 290 using template from another assembly, 314 struct keyword, 357 using template with different types, 310 structs this pointer, 153–156 IntPtr struct, 323 event accessor (add and remove) methods, 193 safe mode, 330 reference types, 153 sealed modifier, 220 static constructors, 153 value struct, 9, 357 value types, 155, 156 ■INDEX 409 thiscall calling convention, 327, 347 passing handle by reference using ^% thread synchronization indirection, 54 SyncRoot property, Array class, 103 return values, 70, 73 threads syntax, 364 asynchronous delegates, 188 using with copy constructors, 55 event accessor (add and remove) trivial properties, 22 methods, 193 TrueForAll method, Array class, 105 static counter variable in initialization, 119 try ... catch block throwing exceptions, 259 error handling for files, 88 handle specific exceptions first, 269 throwing objects, not exceptions, 268 rethrowing in catch block, 269 using multiple finally blocks, 264 throwing exceptions in constructors, 265 walking through invocation list, 187 throwing objects, not exceptions, 266–269 try structured exceptions Find it faster at http://superindex.apress.com at it faster Find warning, 268 interop with, 348–351 thunk, 347 Type class, 279 double thunking, 348 GetAttributes method, 280 Tile constructor, Scrabble game, 129 GetMembers method, 280 Tile struct, Scrabble game, 129 GetMethods method, 280 tilePopulation array, Scrabble game, 131 GetType method, 280 tlbimp.exe tool, 318 InvokeMember method, 280 COM interop, 328 reflecting with Type methods, 280 ToCharArray method, String class, 77, 78 using static method, 280 ToPointer method, IntPtr struct, 347 type identification, 372 ToString method, Array class, 105 Type object enumeration values as strings, 114 getting type information, 280 overrides for, 215 type parameters Scrabble game, 129 class constraints, 297 ToString method, String class, 80 declaring multiple generic parameters, 286 ToXyz methods gcnew constraint, 300 converting from string to primitive generics, 285–286 type, 85 identifier, 286 tracking handles see handles interface constraints, 296 tracking reference operator (%), 66 managed templates and generics tracking references, 52–54 compared, 315 % character, 55 multiple constraints, 303 dereferenced handles, 54 reference type constraints, 303 gc-lvalues and gc-rvalues, 56 reference types and value types as, handles and, 53 298–300 how compilers understand expressions, 56 value type constraints, 301 Out attribute, 272 410 ■INDEX

type safety ■U clr:safe compiler option, 30 UInt16/UInt32/UInt64 types, 12 generic collection classes, 290 unary % operator, 52–53 generic types, 289 unboxing see boxing reinterpret_cast, 209 unified type system, 3 type system implications of, 44–45 CTS (common type system), 3–5 unmanaged resources implications of unified type system, 44–45 examples of, 163 typeid, getting type object, 280 finalizers, 161, 163 TypeInitializationException, 260 handling managed and, 164, 165 typename keyword, 285 wrapper classes for, 163 types unsafe casts, 362 .NET Framework object types, 75 UpdateScore method, Scrabble game, 145 aggregate types, 12–14 UseData function arrays, 92–110 pitfalls of finalizers, 170 compile-time parameterization of using directive, 6, 37–38 types, 27 as_friend modifier, 39 conversion operators, 206–210 COM interop, 328 conversions between strings and other, compilation modes available for, 362 85–86 cross-language interop, 317 dynamic type, 280 scope operator (::), 38 enumerated types, 110–116 using statement, C#, 50 explicitly specifying type argument, 288 generic types, 288–290 ■V GetType method, Array class, 105 value class keyword, 357 inheritance, 45 value classes, 12, 15–17, 365 interfaces and dynamically loaded types, inheritance, 117 255–257 Scrabble game, 127 managed array type, 9, 92–110 sealed modifier, 221 marshaling between native and managed value semantics, 4 code, 327 value struct, 9, 357 mixed types not supported, 14 value struct type, 12 native and managed arrays compared, 101 value tag, XML documentation, 360 parameterized function, 285 value types primitive types, 11–12 abstract classes, 220 runtime parameterization of, 27 as type parameters, 298–300 static type, 280 boxing, 44 String type, 75 changing in function, 65 synonyms for primitive types, 4 constraints, 301–303 using template with different types, 310 ■INDEX 411

controlling when object goes out of VES (Virtual Execution System), 3 scope, 50 virtual accessors, 223 copy constructors, 121 CLS compliant alternative, 321 default constructor for, 118 virtual destructors, 231 defining special member functions, 15 virtual functions explicitly specifying implicit base C++/CLI and C++ compared, 230 classes, 237 compilation modes available for, 363 Hello class, 8 overriding, 215 implicit boxing and unboxing, 45–47 syntax, 370 inheritance, 4, 212 using new keyword on, 214–215 initializing members to default values, 15 using override keyword to implement, 216 introduction, 4 virtual functions in constructors, 228–230 object semantics for, 44 virtual keyword passing as copy, 4 http://superindex.apress.com at it faster Find accessor (get and set) methods of passing as handles, 68–70 properties, 222, 223 passing by reference, 65–66, 69 declaring and implementing passing object by value in C++/CLI, 62 interfaces, 236 passing to functions, 62 virtual machine, 3 reference types compared, 117 virtual methods scope, 4 CLS compliant alternative, 322 table of function signatures, 70 methods implementing interface this pointer, 155 methods, 236 using handle to, 68 using override keyword on, 215–219 using instead of array, 16 virtual properties, 222–225 using this in, 156 visibility value type converted to object, 46 type visibility modifiers, 156 value type with members, 8 Visual Basic varargs, CLS compliant alternative, 322 using interface in, 320 variables Visual C++ 2005 controlling when variable goes out of caveats when upgrading code to, 32 scope, 49 classic compilation, 32 declaring on stack or on heap, 47–52 compilation modes, 30–32 object semantics for reference types, 43 managed extensions syntax, 32 object semantics for value types, 44 mixed mode, 3, 31 tracking references, 53 pure mode, 30–31 vector property see indexed properties safe mode, 30 versions targeting .NET Developer Platform name collisions in inheritance hierarchies, with, 29 212, 213 Void type, 12 412 ■INDEX

■W Write method, Console class, 86 where keyword, 356 Write method, StreamWriter class, 87 whitespaced keywords, 7, 357 WriteLine method, Console class, 81, 86 width field WriteLine method, StreamWriter class, 87 formatting strings using, 82 write-only properties, 22, 183 Win32 API, using, 329 ■X Win32 error codes, interop with, 351–352 x64 architecture, 32 Win32 function xdcmake.exe tool, 359 calling in C++/CLI, 323 XML documentation, 359–362 using in managed class, 331 XML stream Wp64 option Serializable attribute, 273 architecture dependence and 64-bit XmlSerializer programming, 33 serialization attributes, 275 wrappers COM interop, 328 consuming wrapped global function in C#, 320 implicit boxing and unboxing, 45–47 mixing managed/native classes/types, 318 native type thrown from native code, 352 using wrapper from C# assembly, 337 wrapper classes for unmanaged resources, 163 wrapping global function, 319 wrapping MessageBoxClass, 334, 335 wrapping nonexception object, 267