WinRT: Calling C# (CSharp) class libraries from WinJS Javascript

I must say Microsoft is doing a great job with supporting polyglot programming. With .Net CLR support for numerous languages from C#, VB, F#, IronRuby, IronPython and all that - and now WinRT with C++, C# and JS. This post is going to quickly show how you could call a C# class from Javascript within WinRT.

1. Add a class library

I assume you have an existing Javascript Metro Application Project. So now what you have to do is just add a C# Metro Class Library. Add a class. Notice a few rules:

  1. Root namespace has to match assembly name
  2. class has to be sealed
  3. and there's a few more restriction
namespace ClassLibrary1 { public sealed class Class1 { public string test() { return String.Empty; } } }

2. Change type of the project to WinMD

Right click solution, properties, under application tab, change output type to WinMD File.


3. Reference project from the JS Metro Application Project

4. Consume the class from JS

var csharpclass = new ClassLibrary1.Class1(); csharpclass.test();

Read more: Walthrough creating a simple component in C# and calling it from JavaScript

  1. Ronald Widha » Blog Archive » WinRT Consumer Preview: Calling C# (CSharp) Async class libraries from Javascript WinJS.Promises using then() clause says:

    [...] probably already know that you can call C# Class Libraries from WinJS. Now that means I can define C# async methods and call it with WinJS.Promises [...]