Value classes and structs (C++/CX)

1 out of 4 rated this helpful - Rate this topic

A value struct or value class is a Windows Runtime-compatible POD ("plain old data structure"). It has a fixed size and consists of fields only; unlike a ref class, it has no properties.

The following examples show how to declare and initialize value structs:


// in mainpage.xaml.h:
    value struct TestStruct
    {
        Platform::String^ str;
        int i;
    };

    value struct TestStruct2
    {
        TestStruct ts;
        Platform::String^ str;
        int i;
    };


// in mainpage.cpp:
    // Initialize a value struct with an int and String
    TestStruct ts = {"I am a TestStruct", 1};

    // Initialize a value struct that contains
    // another value struct, an int and a String
    TestStruct2 ts2 = {{"I am a TestStruct", 1}, "I am a TestStruct2", 2};

    // Initialize value struct members individually.
    TestStruct ts3; 
    ts3.i = 108;
    ts3.str = "Another way to init a value struct.";



When a variable of a value type is assigned to another variable, the value is copied, so that each of the two variables has its own copy of the data. A value struct is a fixed-size structure that contains only public data fields and is declared by using the value struct keyword.

A value class is just like a value struct except that its fields must be explicitly given public accessibility. It's declared by using the value class keyword.

A value struct or value class can contain as fields only fundamental numeric types, enum classes, or Platform::String^. Except for String, a value class or struct cannot have a ref class or struct as a member.

Because all members of a value class or value struct are public and are emitted into metadata, standard C++ types are not allowed.

The following code fragment declares the Coordinates and City types as value structs. Notice that one of the City data members is a GeoCoordinates type. A value struct can contain other value structs as members.


public enum class Continent 
{  
    Africa,
    Asia,
    Australia,
    Europe,
    NorthAmerica,
    SouthAmerica,
    Antarctica 
};

value struct GeoCoordinates
{
    double Latitude; //or float64 if you prefer
    double Longitude;
};

value struct City
{
    Platform::String^ Name;
    int Population;
    double AverageTemperature;
    GeoCoordinates Coordinates;
    Continent continent;
};


Did you find this helpful?
(1500 characters remaining)
© 2013 Microsoft. All rights reserved.