JavaScript and .NET Arrays in Silverlight

Michael Schwarz on Friday, June 1, 2007

During my tests with the DLR (Dynamic Language Runtime) in Silverlight 1.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.

<strong>How can I create a byte array?</strong>

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 = <span class="kwrd">new</span> System.Collections.ArrayList();

<span class="kwrd">for</span>(var i=0; i&lt;inputArray.length; i++) list.Add(inputArray[i]);

<span class="kwrd">return</span> list.ToArray(System.Byte.UnderlyingSystemType); }</pre>

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:

<pre class="csharpcode">from System.Collections.Generic import List
from System import Byte

s = ListByte [2] s.Add(58) s.Add(32)

<span class="rem">// the byte[] array you get with following line</span> ba = s.ToArray()</pre>

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