Windows Runtime methods cannot be generic - Reasons, Workarounds, Alternatives?
Asked Answered
G

2

14

Here is an Interface, taken from my attempt to port MemBus, an Event Aggregator I maintain, to the Windows runtime world:

public interface ISubscriber
{
    IDisposable Subscribe<M>(Action<M> subscription);

    #if WINRT 
    [Windows.Foundation.Metadata.DefaultOverload]
    #endif
    IDisposable Subscribe(object subscriber);

    IObservable<M> Observe<M>();
}

What I am getting is a Compiler error:

"error WME1031: 'MemBus.ISubscriber.Subscribe<M>(System.Action<M>)' is a generic method. Windows Runtime methods cannot be generic."

I have only suspicions as to why this is the case, if anybody can clarify, please do.

My main question is: How are we supposed to deal with this when porting code to the Windows runtime?

A lot of higher Level functionality happens with generics. In fact, we use generic classes in the Windows Runtime (e.g. List<T>). How is a RT component supposed to expose generic types, and if not, is the only alternative available to go back to the ways of writing .NET 1.1 code, i.e. object in, object out and do casts?

Groce answered 4/9, 2012 at 16:50 Comment(0)
C
12

You need to choose a Class Library template from the Windows Store templates (not the Windows Runtime Component template).

Screenshot VS2012

This will allow you to use the full C# language in a Windows Store app, but won't allow other languages like C++ and JS to consume the assembly (as they don't support generics in the same way that C# does).

Conferral answered 5/9, 2012 at 7:39 Comment(1)
I am marking this as an answer, as I was thinking about porting. When porting a .NET library that was meant to be consumed primarily by other .NET languages it seems to make sense to restrict yourself to targetting C# and skipping C++/Javascript support in favor of keeping many constructs known to C# dev for many years. When it comes to new development, the answer may be a different one.Groce
F
6

The short story is that JavasScript does not know how to handle generics, so a WinRT component cannot use them. See WinRT reason for disallowing custom generic types or interfaces for a longer discussion.

Fourier answered 4/9, 2012 at 23:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.