Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


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


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








