Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 233
Claire Novotny Avatar asked Oct 19 '12 19:10

Claire Novotny


People also ask

How do you avoid null reference exception?

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.

What is a null reference 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.

How do I fix null reference exception in C#?

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.


1 Answers

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.

like image 132
James McNellis Avatar answered Oct 22 '22 15:10

James McNellis