JavaScript and .NET Arrays in Silverlight

Tags: .NET, DLR, JavaScript, Silverlight, WPFE

During my tests with the DLR (Dynamic Language Runtime) in Silverlight 1.1 I came accross several things that didn't work first. Most of them could be fixed by using small workarounds.

Managed JavaScript (compared with IronPython) does not support generics or .NET arrays. Those features require changes or additions to the language syntax, and therefore are not yet implemented. The main focus on the first version of managed JavaScript was to be EcmaScript compatible.

How can I create a byte array?

The simplies way is to create a helper function that will get a JavaScript array as argument and will return a .NET byte array.

function ConvertToByteArray(inputArray)
{
   var list = new System.Collections.ArrayList();
   
   for(var i=0; i<inputArray.length; i++)
      list.Add(inputArray[i]);

   return list.ToArray(System.Byte.UnderlyingSystemType);
}

This helper function can convert a JavaScript array to a byte array to be passed to .NET methods (i.e. IsolatedStorageFile.Write(...)).

In IronPython generics are already supported, so you can use a List of Byte:

from System.Collections.Generic import List
from System import Byte

s = List[Byte]()
s.Add(58)
s.Add(32)

// the byte[] array you get with following line
ba = s.ToArray()

In future releases this will be changed, I hope so, and will be more transparent.

No Comments