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
Use Null Coalescing to Avoid NullReferenceExceptions It works with all nullable data types. The following code throws an exception without the null coalescing. Adding “?? new List<string>()” prevents the “Object reference not set to an instance of an object” exception.
A NullReferenceException exception is thrown when you try to access a member on a type whose value is null . A NullReferenceException exception typically reflects developer error and is thrown in the following scenarios: You've forgotten to instantiate a reference type.
Solutions to fix the NullReferenceException To prevent the NullReferenceException exception, check whether the reference type parameters are null or not before accessing them. In the above example, if(cities == null) checks whether the cities object is null or not.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With