1

I have the following method

    private void PushToMainWindow(UserControl child) // where child is IMainWindowPlugin
    {
        _navigationStack.Push((IMainWindowPlugin)child);
        ...
        // Here I do stuff that makes use of the child as a usercontrol
        child.Width = 500;
        child.Margin = new Thickness(0,0,0,0);
        ...
    }

What I would like to do is inform the compiler that I'll only be accepting UserControl objects that also implement the IMainWindowPlugin interface.

I know I can do a if statement and throw or cast and check for null, but those are both run-time solutions, and I'm looking for a way to tell the developer up front that there is a restriction on the type of UserControl he can add. Is there a way to say this in c# ?

UPDATE: Added more code to show that the usercontrol is used as a usercontrol, so I can't just pass the child as the interface.

user230910
  • 2,353
  • 2
  • 28
  • 50
  • If IMainWindowPlugin is your interface you can create base class that inherits from UserControl and have empty implementation for this interface. Also check this one: http://stackoverflow.com/questions/178333/multiple-inheritance-in-c-sharp – Amittai Shapira Sep 03 '15 at 08:27

3 Answers3

3

Have you consider generics? Something like this should work:

    private void PushToMainWindow<T>(T child) where T: UserControl, IMainWindowPlugin
    {
        var windowPlugin = child as IMainWindowPlugin;
        _navigationStack.Push(windowPlugin);
        ...
        // Here I do stuff that makes use of the child as a usercontrol
        child.Width = 500;
        child.Margin = new Thickness(0,0,0,0);
        ...
    }

Compiler will not allow for passing to the PushToMainWindow() method objects that are not meeting the where clause, which means that the class you are passing has to be UserControl (or derived) and implement IMainWindowPlugin.

Other thing is, that probably passing the interface itself is better idea, instead of basing on concrete implementation.

jjczopek
  • 3,319
  • 2
  • 32
  • 72
0

Why not

void PushToMainWindow(IMainWindowPlugin child) { ... }
Richard Schneider
  • 34,944
  • 9
  • 57
  • 73
0
 private void PushToMainWindow(IMainWindowPlugin child) 
    {
        _navigationStack.Push(child);
        var newChild=(UserControl )child
        newChild.Width = 500;
        newChild.Margin = new Thickness(0,0,0,0);
    }
Arash
  • 889
  • 7
  • 18