none
global const Array

    Question

  • Hi!

    I am just playing around with VC++ Express 2005. I am trying to port some old example sources to .NET. This is much more difficult than expected.

    Have a look on this:

    class Constant
    {
    public: 
       String Name;
       double Value;
    };

    static const Constant ConstTable[] =      // global scope
    {
       {"e", 2.718281828},
       {"Pi", 3.14159265358979323846},
       
    {"c", 299792458.0}

    };

    Okay. "String" was a custom type. I didn't want to port it. So I used the .NET pendant "String" in "class Constant". This forces me to make the "class Constant" a managed type (using "ref") because an unmanaged class can't contain managed members. After this, the compiler complains that no native arrays can be created of an managed type.

    How can this be solved? On the one hand I want to create an global const array of a class type, and on the other hand I want to use no other string classes than String and StringBuilder. How can I solve this in a .NET and managed-C++ friendly manner?

    Thanks!

    Saturday, June 04, 2005 8:48 PM

Answers

  • Here is a simple solution using managed code:

    value class Constant
    {
    public:
        String^ Name;
        double Value;
    };

    ref struct StaticClass abstract sealed
    {
        static initonly array<const Constant>^ ConstTable =
        {
            { "e", 2.718281828 },
            { "Pi", 3.14159265358979323846 },
            { "c", 299792458.0 }
        };
    };

    A few things are worth noting: A value class is used for defining Constant since ref classes don’t qualify as aggregate types. Value classes are also more efficiently stored and accessed in memory and are stored continuously in the managed array. An abstract sealed class is used to house the static array since managed types cannot be global variables.

    Cheers,
    Kenny Kerr

    http://weblogs.asp.net/kennykerr/

    Monday, June 06, 2005 7:31 AM