Implementation of interface when using child class of a parent class in method of interface

I don't have access to my dev environment, but when I write the below:

interface IExample
 void Test (HtmlControl ctrl);



 class Example : IExample
 {
     public void Test (HtmlTextArea area) { }

I get an error stating the methods in the class implementation don't match the interface - so this is not possible. HtmlTextArea is a child class of HtmlControl, is there no way this is possible? I tried with .NET 3.5, but .NET 4.0 may be different (I am interested in any solution with either framework).

Thanks

Answers


interface IExample<T> where T : HtmlControl
{
    void Test (T ctrl) ;
}

public class Example : IExample<HtmlTextArea>
{
    public void Test (HtmlTextArea ctrl) 
    { 
    }
}

Note for Charles: You can use generic to get strongly typed method, otherwise you do not need to change signature of the method in child class, but just call it with any child of HtmlControl


In the interface, it's saying any HtmlControl can be passed. You're narrowing the scope, by saying only a HtmlTextArea can be passed in, so no, you can't do this :)

Picture this example for the reasoning:

var btn = new HtmlButton(); //inherits from HtmlControl as well

IExample obj = new Example();
obj.Test(btn); //Uh oh, this *should* take any HtmlControl

You can do it with generics. Give the interface a type parameter which is constrained to HtmlControl and its children. Then in your implementation you can either use HtmlControl or a descendant. In this example I'm using HtmlControl, but I'm invoking the Test() method with both HtmlControl and HtmlTextArea:

public class HtmlControl {}
public class HtmlTextArea : HtmlControl { }

// if you want to only allow HtmlTextArea, use HtmlTextArea 
// here instead of HtmlControl
public interface IExample<T> where T : HtmlControl
{
    void Test(T ctrl);
}

public class Example : IExample<HtmlControl>
{
    public void Test(HtmlControl ctrl) { Console.WriteLine(ctrl.GetType()); }
}

class Program
{
    static void Main(string[] args)
    {
        IExample<HtmlControl> ex = new Example();
        ex.Test(new HtmlControl());    // writes: HtmlControl            
        ex.Test(new HtmlTextArea());   // writes: HtmlTextArea

    }
}

Need Your Help

SQL: Double if statement/database query issue

php mysql sql

I'm a bit of a rookie to SQL and PHP coding, but am trying to do the following:

(C#) iterate over read-only private collection member

c# iteration hashset private-members

I have a class which has two HashSet&lt;String&gt; collections as private members. Other classes in my code would like to be able to iterate over those HashSets and read their contents. I don't w...