Search code examples
c#javascriptnullwindows-runtimeprojection

How should I work around WinRT JS saying null is "null"?


So I recently had a face-palm moment with Javascript and WinRT. Basically, I'm developing a WinRT API, so it should work well with Javascript, C++, and C#. I have a property in the API that does special stuff if the passed in value is null. So, for instance:

public string Foo
{
  get
  {
    return foobar.ToString();
  }
  set
  {
    if(string.IsNullOrEmpty(value))
    {
      foobar=SomeSpecialValue;
      return;
    }
    ParseIntoFoobar(value);
  }
}

This seems like a perfectly fine property to me. However, when you use something like this from Javascript:

myFoobar.foo=null;

The result is a parsing exception thrown from ParseIntoFoobar Why? Because apparently the value of null in Javascript is "null" as in a string containing the word null`

From the documentation I've seen, this should result in either a conversion to null for C#, or it should result in an empty string, not this goofy result. In fact, you can make some really unintuitive behavior that makes no sense to me. Projection:

public string Biz{get;set;}

Javascript:

myObject.biz=null;
log(myObject.biz==null); //results in false

What is the best way to work around this "feature"? What should I do about things where I want to detect null, but where "null" as a string isn't exactly invalid? (think username or some such)


Solution

  • You could just use empty string "" (string.Empty) which will be universally accepted.

    My "guess" about why null isn't acceptable is probably because of some type mapping trickery that is happening to make everything compatible. C++ might be doing something weird like translating a null reference into a '\0' (null character), which would then be an empty string.