tags:

views:

216

answers:

3

I am attempting to bind c# generics to a class and an interface like this:

public class WizardPage<T> where T : UserControl, IWizardControl 
{
    private T page;

    public WizardPage( T page ) {
        this.page = page;
    }
}

And use it with this:

public class MyControl : UserControl, IWizardControl {
   //...
}

Somehow C# doesn't seem to be able to decide that MyControl is a proper instance of T as

public class Wizard<T> where T : UserControl, IWizardControl {

    private WizardPage<T> Page1;

    public Wizard( MyControl control ) {
        this.Page1 = new WizardPage(control);
    }
}

fails with error

The best overloaded method match for 'Controls.WizardPage<T>.WizardPage(T)' has some invalid arguments

Am I doing something wrong or is this just not going to work?

A: 

I don't get the Wizard class. Shouldn't it rather be something like this:

public class MyWizard : WizardPage<MyControl>{ 
    public MyWizard( MyControl control ) : base(control) { } 
} 
klausbyskov
No. Wizard manages pages and transitions between them while WizardPages themselves are merely listening to the relevant UserControl and attach to certain events via IWizardControl interface.Simple solution would just be to create abstract WizardControl class to derive from that would extend UserControl and implement IWizardControl, but I wanted to try if there were more elegant solution available.
plouh
A: 

you have to declare the type used :

this.Page1 = new WizardPage<MyControl>(control);
remi bourgarel
This I tried already, but it says "cannot implicitly convert to type".
plouh
+2  A: 

Your Wizard class should probably look something like this:

public class Wizard<T> where T : UserControl, IWizardControl
{
    private WizardPage<T> Page1;

    public Wizard(T control)
    {
        this.Page1 = new WizardPage<T>(control);
    }
}

Or, if you don't need the class itself to be generic you could do something like this instead:

public class Wizard
{
    private WizardPage<MyControl> Page1;

    public Wizard(MyControl control)
    {
        this.Page1 = new WizardPage<MyControl>(control);
    }
}
LukeH
This far I got that I had it working in the latter form. Unfortunately I cannot then have a private WizardPage<T> ActivePage;member variable as it needs to be generic. The first syntax just didn't work, It only created the same errors as before.Maybe I just store the IWizardControl reference as the UserControl stuff I don't need afterwards.
plouh