Home

Techniques of Implementing Properties

 

Static Properties

Like a regular member variable, a property van be created as static. To do this, precede its name with the static keyword. A static property can implement only the behavior of a static member variable. Here is an example:

public ref class CComputerInventory
{
private:
    static String ^ name;

public:
    property static String ^ ComputerName
    {
	String ^ get() { return name; }
	void set(String ^ nm) { name = nm; }
    }
};

After creating a static property, you can access it outside using the . or the -> operators. Because it is static, you can also access it using the :: operator applied to the name of the class. Here are examples:

using namespace System;

public ref class CComputerInventory
{
private:
    static String ^ name;
    static String ^ mnUser;

public:
    property static String ^ ComputerName
    {
	String ^ get() { return name; }
	void set(String ^ nm) { name = nm; }
    }

    property static String ^ MainUser
    {
	String ^ get() { return mnUser; }
	void set(String ^ user) { mnUser = user; }
    }
};

void ListComputer(CComputerInventory ^ cInv)
{
    Console::WriteLine(L"Computer Inventory");
    Console::WriteLine(L"Computer Name: {0}", cInv->ComputerName);
    Console::WriteLine(L"Main User:     {0}", cInv->MainUser);
}

int main()
{
    CComputerInventory ^ inv = gcnew CComputerInventory;
    CComputerInventory::ComputerName = L"CNTLWKS228";
    CComputerInventory::MainUser     = L"Gertrude Monay";

    ListComputer(inv);

    Console::WriteLine();
    return 0;
}

This would produce:

Computer Inventory
Computer Name: CNTLWKS228
Main User:     Gertrude Monay

Press any key to continue . . .

A Class Property

As done for a primitive type, you can create a property that is based on a class. If the class is managed, type the ^ operator between the class's name and its property name. We will see an example in Lesson 16.

A Property as a Handle

All of the properties we have created so far were of primitive types in the stack. You can also create a property in the managed heap. To do this, type the ^ operator between its data type and its name.

Inheriting a Property

When you derive a class from another, the new class inherits the (public) properties of the parent class. This is one of the most valuable characteristics of properties.

 

Previous Copyright © 2006-2007 FunctionX, Inc. Home