Search code examples
c#interfacecastingextend

How to load a class which extended from a form and interface?


I have few forms class which extended based Form and my custom interface.

Interface InterfaceForms{
      void InterfaceFunc1();
}



public partial class child1 : Form, InterfaceForms
    {
      public child1(){}
      public InterfaceFunc1(){}
    }

public partial class child2 : Form, InterfaceForms
    {
      public child2(){}
      public InterfaceFunc1(){}
    }

I added all the form classes object to a list as below:

 List<Form> lsf = new List<Form>();

then I tried to load the my form classes as below:

 var fr = from Form item in lsf
                         where item.Name == "child1"
                         select item;
Form frm = (Form)fr;

Now, my problem is I cannot access to InterfaceFunc1().

Would you mind advising me how I can implement this? Please take note that frm type might be diffrent each time (child1, child2 & etc) but all of them are extended from Form and InterfaceForm.


Solution

  • You need to cast it as InterfaceForms:

    var fr = from Form item in lsf
                             where item.Name == "child1"
                             select item;
    Form frm = (Form)fr;
    var iFaceFrm = frm as InterfaceForms;
    
    if (iFaceFrm != null)
    {
        //use the iFaceFrm or frm here
    }
    

    Edit

    The issue with your LINQ statement is declaring the type, the type of a LINQ statement is inferred, so you don't put it in the select:

    var fr = from item in lsf
             where item.Name == "child1"
             select item;
    

    Or, if you want to do it proceduraly:

    var fr = lsf.Where(f => f.Name == "child1").FirstOrDefault();