Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hey i was here to day playing around with interfaces to try get better to them (cos i never use anything but abstract classes cos i never feel interfaces is much of use) but i have made the following code:

class Program
    {
        static void Main(string[] args)
        {
            List<maintestclass> tl = new List<maintestclass>() { new testclass(), new testclass(), new testclass2()};
            List<testinterface> ti = new List<testinterface>();

            Console.ReadLine();
        }
    }

    public class testclass : maintestclass, testinterface
    {
        public void testmetode()
        {
            Console.WriteLine("interface call");
        }
    }

    public class testclass2 : maintestclass
    {
    }

    public abstract class maintestclass
    {

    }

    public interface testinterface
    {
        void testmetode();
    }


and what i really wanna do is to parse every object in "tl" that can inherit from testinterface to ti but it seems i cant make it to work, i've tried to use "where" and get type but cant find a usefull way to do it...

if anyone fast could help me i would be greatfull. (sample codes would help alot)

- Jackie
Posted
Updated 16-May-12 7:37am
v2

1 solution

If I understood correctly, you can cast an object instance to your interface like:

C#
testinterface someVar = originalVar as testinterface;

after that someVar should contain the variable as your interface if the original instance implemented the interface. If it didn't, someVar is null.
 
Share this answer
 
Comments
Jackie00100 16-May-12 13:53pm    
Thanks is there a way to do this by using .where on a list?
lewax00 16-May-12 14:16pm    
Something like this?
Where(x => (x as testinterface) != null)
Wendelius 16-May-12 14:28pm    
Yep, just like that :)
Jackie00100 16-May-12 14:39pm    
keep getting "Error: Cannot convert type 'System.Collections.Generic.List<interfacetest.maintestclass>' to 'System.Collections.Generic.List<interfacetest.testinterface>'"

this code is the problem: ti = (List<testinterface>)tl.Where(x => (x as testinterface) != null).ToList();

Thanks alot for helping :)
Wendelius 16-May-12 14:44pm    
How are ti and tl defined?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900