Wednesday, May 5, 2010

Silverlight 4, Javascript, and C# 4's dynamic keyword

The .NET 4 framework was released last month in April and along with it came C# 4.0. Among the many features added in Microsoft's new iteration of C#, the dynamic keyword was a major one. The keyword simplifies interop between dynamic languages and C#, which can come in handy when dealing with COM objects and others. Fortunately, this feature plays well with Silverlight 4 and, as a result, allows for easy communication between C# and JavaScript. Although it was already possible in previous versions of Silverlight, the dynamic keyword makes it much easier to communicate between the two languages.

First, if you haven't already done so, you will need the following using statements in your code in order to use the HtmlPage class.
using System.Windows.Browser;

Now, we can get started on calling JavaScript from C# using dynamic.  We need to access the underlying HTML page that contains our JavaScript code, so we will use the HtmlPage class to do so and assign it to a dynamic variable.
dynamic htmlWindow = HtmlPage.Window;

Now we can invoke JavaScript methods on the page using the htmlWindow variable and receive return values as well.  To do this, we simply call the JavaScript function as we would call a function that is in a class.
dynamic sum = htmlWindow.addWithJavaScript(10, 13);

The JavaScript function is as follows
function addWithJavaScript(var1, var2)
{
    var sum = var1 + var2;
    alert("JS sum: " + sum);
    return sum;
}

Together, the C# code is very concise and only takes two lines to communicate with JavaScript
dynamic htmlDocument = HtmlPage.Window;
dynamic sum = htmlDocument.addWithJavaScript(10, 13);
MessageBox.Show("C# return value: " + sum); // Just to show the results in C# 
For more information on the dynamic keyword in C# and the DLR
http://msdn.microsoft.com/en-us/library/dd264741.aspx (C# Dynamic)
http://msdn.microsoft.com/en-us/library/dd233052.aspx (DLR)