locked
String empty, Null pointer

    Question

  • Hi, I'm getting a NullReferenceException, could someone explain me this behavior please ?


    String^ s = ref new String( L"" ); // Empty. Test( s ); void Test( String^ s ) { if ( s == nullptr ) { throw ref new NullReferenceException( ); // !? } }


    Friday, March 23, 2012 5:05 PM

Answers

  • I took a look at http://msdn.microsoft.com/en-us/library/windows/apps/hh699879(v=vs.110).aspx   Platform::String

    As soon as you did:   String^ s = ref new String( L"" );

    s is 0x0000000000 according to the debugger.So Platform::String is quite different than  std::string. std::string is mutable, and can contain the 0 character, possibly multiple times.   Platform::String is non-mutable and cannot contain the 0 char.     

    Assuming that null is encoded with a null pointer, the empty string must be treated as a null pointer.

       bool IsEmpty()
     
    true if the current String object is null or the empty string (L""); otherwise, false.
    

    • Marked as answer by t-n-x Sunday, March 25, 2012 2:26 AM
    Saturday, March 24, 2012 8:47 PM

All replies

  • I took a look at http://msdn.microsoft.com/en-us/library/windows/apps/hh699879(v=vs.110).aspx   Platform::String

    As soon as you did:   String^ s = ref new String( L"" );

    s is 0x0000000000 according to the debugger.So Platform::String is quite different than  std::string. std::string is mutable, and can contain the 0 character, possibly multiple times.   Platform::String is non-mutable and cannot contain the 0 char.     

    Assuming that null is encoded with a null pointer, the empty string must be treated as a null pointer.

       bool IsEmpty()
     
    true if the current String object is null or the empty string (L""); otherwise, false.
    

    • Marked as answer by t-n-x Sunday, March 25, 2012 2:26 AM
    Saturday, March 24, 2012 8:47 PM
  • This is really a dangerous behavior for a C++/CLI or C# programmer, the .NET String^ can be non-null and empty.

    Thanks for the explanation : )

    Sunday, March 25, 2012 2:40 AM
  • I would like to hear an authoritative explanation from Microsoft too.  I don't understand technically why an automatic convert to and from  std::wstring would not be useful. 

    Sunday, March 25, 2012 3:01 AM