Exception when trying to read null string in C# WinRT component from WinJS
Asked Answered
I

1

13

I have the following scenario: Data lib in C# compiled as a Windows Runtime component.

One of its classes is looks like this:

public sealed class MyData
{
  string TheGoods { get; private set;}
}

The UI is in WinJS, and I have the following:

var b = dataInstance.theGoods;

The problem is that I get an exception and property has the following in it:

System.ArgumentNullException at System.StubHelpers.HStringMarshaler.ConvertToNative(String managed)

Looking at the implementation of HStringMarshaler.ConvertToNative, it seems to throw if the string is null.

Does that mean that it's impossible to expose a null string to WinJS? Is that a WinJS limitation or does that apply to all WinRT?

While string.Empty does work, that's not semantically the same as null and in some cases, empty is valid and different than null.

If I change the type of the property to be 'object', then it does work, but it seems nasty to expose an object when it really ought to be a string. Any ideas? The docs are pretty light on this

Incept answered 19/10, 2012 at 19:13 Comment(0)
D
15

The Windows Runtime string type is a value type and has no null value. The .NET projection prohibits passing a null .NET string across the Windows Runtime ABI boundary for this reason.

The string type used by the Windows Runtime is the HSTRING type. While this type does not have a null value, it does have a null representation (that is, in C++, HSTRING s = nullptr; is valid). An HSTRING with a null representation is an empty string.

The .NET projection converts this null representation into an empty string (String.Empty) for strings coming in from the ABI boundary, and prohibits actual null .NET strings from being passed back across the ABI boundary.

Disport answered 19/10, 2012 at 19:26 Comment(3)
So for C#, would it be safe to say that class constructors should initialize the strings to string.Empty? It would be nice if the docs were updated to mention it. msdn.microsoft.com/en-us/library/windows/apps/…Incept
Well, that depends. The .NET string type is still a reference type and may be null. It's only when passing a string across the ABI boundary that null is not permitted (i.e., when the .NET string is converted to a Windows Runtime HSTRING). So, perhaps there are still cases where null strings are useful, you just need to be sure to check strings before they cross the ABI boundary.Disport
Right...so for those types that are returned to WinRT, either directly or via interface, strings should be initialized as empty. Thanks!Incept

© 2022 - 2024 — McMap. All rights reserved.