Windows 8 programming model allows extending WinRT by implementing WinRT components. These components can be created by using any supported language (JS, C#, VB, C++) and can be consumed by all these languages as well.

Visual Studio provides WinRT library project template, thus creation of your first WinRT component is matter of seconds. Gradually, you will find that your code should follow some rules to stay compatible with WinRT. Most of these rules are not deal breaker, but sometimes they can make you scratch your head a bit.

For example, one of the rules for C# states that all public classes (except XAML controls) must be sealed and custom WinRT-enabled class cannot be inherited from another custom WinRT class. But what can be done to expose a complex hierarchy of objects via WinRT?

Here is the solution. Unlike for classes, inheritance is allowed for public interfaces. At the same time there are no restrictions for private classes, so a combination of public interfaces and hierarchy of private classes can be used.

To demonstrate this approach I will use hierarchy of three classes – Publication (base class), Book and Magazine (are derived from Publication).

First, I need to introduce interfaces:


public interface IPublication
{
   string Publisher { get; set; }
   string Name { get; set; }
}

public interface IBook : IPublication
{
   string Author { get; set; }
}

public interface IMagazine : IPublication
{
   string Category { get; set; }
}

Then I can implement these interfaces (note that classes are private):


class Publication : IPublication
{
   public string Publisher { get; set; }
   public string Name { get; set; }
   // ...
}

class Book : Publication, IBook
{
   public string Author { get; set; }
   // ...
}

class Magazine : Publication, IMagazine
{
   public string Category { get; set; }
   // ...
}

But now my WinRT library exposes only interfaces and I need to provide some mechanism to instantiate objects that implement these interfaces. For example PublicationFactory:


public sealed class PublicationFactory
{
   public IBook CreateBook()
   {
      return new Book();
   }

   public IMagazine CreateMagazine()
   {
      return new Magazine();
   }
}

As the result I have WinRT library that exposes structured hierarchy of classes and allows Metro-style apps using this library to take all the advantages of object oriented design.

Download sample project - WinRTLibrary.zip

blog comments powered by Disqus