3

Scenario:
I have 3 classes (A,B,C) in my Windows Runtime Component project.

class A{}
public sealed class B : A {}
public sealed class C : A {}

On compiling the above code, I get the following error:

"Inconsistent accessibility: base class 'A' is less accessible than class 'C'."

If I make class A public, it gives a compile error :

"Exporting unsealed types is not supported. Please mark type 'MyProject.A' as sealed."

But now, if I make A as sealed, then B and C cannot inherit from it.

Considering the fact that only WinRT types are allowed for inheritance, is it anyhow possible to use custom/user-defined classes for inheritance? If not, is there any workaround to achieve the same?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
Raunak Yadav
  • 119
  • 1
  • 1
  • 7
  • 2
    The ability to have Javascript or native C++ directly execute your code, languages that have no support for inheritance or do it a dramatically different way, does come with a few compromises of course. Either A must be an interface or you'll have to encapsulate it. If client code is only C# then use a regular class library instead. – Hans Passant Mar 31 '16 at 13:43
  • 1
    @HansPassant wouldnt that be a perfectly fine answer to the question? – Domysee Mar 31 '16 at 13:50
  • Everybody likes happy answers, I have no interest in having to support unhappy ones. – Hans Passant Mar 31 '16 at 13:54
  • @HansPassant I already have the completed class library with all good things like inheritance in place. But due to new requirements (supporting other languages C++/JS), a winRT component is to be given for the same project. After working on class library, winRT seems to be so much restricting. :( – Raunak Yadav Mar 31 '16 at 20:18

1 Answers1

1

As you've figured out by yourself, you can't expose classes that inherit from others in a Windows Runtime Component; that is true even if you try to use an abstract class as a parent class. This is a "drawback" needed to make WinRT components works with all the others languages that the WinRT framework supports. The only way to workaround this is avoiding inheritance. You can only use interfaces or object composition where you can simulate inheritance behaviors, e.g.:

public sealed class A
{
    public void Method() { }
}
public sealed class B
{
    A a;

    public void Method()
    {
        // Do B stuff

        // Call fake "virtual" method
        a.Method();
    }
}
Tommaso Scalici
  • 480
  • 1
  • 6
  • 15