Browse DevX
Sign up for e-mail newsletters from DevX


Book Excerpt: Essential Guide to Managed Extensions in C++ : Page 2

Managed Extensions for C++ are added to the Visual C++ .NET compiler to allow access to .NET Framework functionality. Visual C++ .NET is the only .NET language that can generate both native and managed code, and its rich set of features let you write managed applications for the .NET platform. This comprehensive guide to coding managed extensions for C++ was written by key members of the Visual C++ .NET compiler development teampeople who have spent most of their time implementing the language and educating others about managed C++. Read Chapter 9, ''Properties.''




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Scalar and Indexed Properties
The common language runtime supports two types of properties: scalar and indexed. The MC++ compiler also supports both of them.

A scalar property is defined by a getter that does not take any parameters and a setter that takes exactly one parameter. A property is indexed if the getter takes one or more parameters and the setter takes more than one parameter.

To illustrate managed properties, let's consider the following scenario.

Imagine that you need to design a database of students. Given a student's name or ID, this simple database should be able to return the student's address. Here is how you can do it:

#using <mscorlib.dll> using namespace System; __gc class Student { String*name_; String*address_; /*...*/ public: __property String*get_Address(){return address_;} __property void set_Address(String*address ) {address_=address;} /*...*/ }; __gc class Database { Student*students_[]; int MapNameToId(String*name ); public: __property String*get_Address(int id ) { return students_[id ]->Address; } __property String*get_Address(String*name ) { int id =MapNameToId(name ); return students_[id ]->Address; } protected: __property void set_Address(int id,String *address ) { students_[id ]->Address =address; } __property void set_Address(String*name,String *address ) { int id =MapNameToId(name ); students_[id ]-> Address =address; } }; Database*OpenDatabase();

Access to a student's address(es) is now achieved as follows:

int main() { Database*pDatabase =OpenDatabase(); String*address1 =pDatabase->Address ["John "]; String*address2 =pDatabase->Address [89640 ]; }

In the preceding sample, method Student::get_Address takes no arguments and returns a String*. This is an example of a scalar property. In contrast, Database::get_Address takes an argument, an index. That's why this kind of property is called indexed.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date