Tip of the day: Using Constants in WinRT

This tip comes courtesy of a question asked on an internal discussion list. Deon from the C++ team provided the answer.

WinRT does not support constants. This means you cannot have code such as the following in C++ /CX:

public ref class FooClass sealed

{

public:

const int FooValue = 42;

}

How does one mimic constants with C++ /CX? Turns out using a static property is the solution.

namespace Foo

{

    public ref class FooClass sealed

    {

    public:

        static property int Value

        {

            int get()

            {

                return x;

            }

            void set(int _value)

            {

                x = _value;

            }

        }

    private:

        static int x;

    };

}

Having static properties allows you to write code as follows:

Foo::FooClass::Value = 42;

int i = Foo::FooClass::Value; 

Better, this code now works if you want to access such properties from other WinRT supported languages such as JS, C# etc.

Enjoy!

-Sridhar