vendredi 31 juillet 2015

Declaring, updating and accessing a System::String within a class

I've been searching since yesterday about my question but I found nothing related to it so far. By the way, I am quite new to classes so please be kind.

I declared a System::String variable within a class, I created a method to update that variable and another one that returns it's value. However, updating the said variable throws an exception. What is the correct way of declaring a System::String within a class and how do you update and return it's value from a class?

The exception:

A first chance exception of type 'System.NullReferenceException' occurred in XXX.exe

Here is the simplified version of the class I made:

ref class clTimeStamp {
public:
    clTimeStamp()
    {
        strDatestamp = gcnew System::String("");
    }
private:
    System::String ^strDatestamp;
public:
    void SetDateStamp(System::String ^a)
    {
        strDatestamp = a->Substring( 6, 4 );    // yyyy
        strDatestamp = strDatestamp + "-" + a->Substring( 3, 2 );
        strDatestamp = strDatestamp + "-" + a->Substring( 0, 2 ) + "T";
    }
    System::String ^GetDateTimeStamp()
    {
        return strDatestamp;
    }
};

And this is how I used it in the main program:

strBuffer = gcnew String(buffer.c_str());
clTimeStampHSCAN1->SetDateStamp(strBuffer);
fprintf(handle, "%s\n", clTimeStampHSCAN1->GetDateTimeStamp());

I am really confused with strings in C++-CLI, there's just too many ways to create them and it gets quite complicated.

Your help will be greatly appreciated.

Edit: Updated with Caninonos' suggestion (change initialization of String variable in the constructor) but the result is still the same.

Aucun commentaire:

Enregistrer un commentaire