Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Interface Type As Parameter

I already know that you can pass an interface as a parameter to a method. This allows you to specify only the relevant members of an object required by a method. What I would like to do is to be able to pass an interface type as a parameter.

Say I declared several interfaces, which were implemented un-evenly across a range of objects that all form a single list/collection. Could I write a helper method which would take both an object from the list and an interface type as a parameter, and check if the object implements the interface? The following code is obviously rubbish, but it illustrates the sort of thing I want to do:

private bool CheckType(object o, interface intrfce)
{
    try
    {
        object x = (object)(intrfce)o;
        return true;
    }
    catch (InvalidCastException e) 
    {
        return false
    }
}

At the moment I'm simply planning on setting up an enum for the interfaces, and requiring all classes to expose an array/list of interfaces they implement. I can then just check the enum list to see what interfaces they have that are relevant (I'm only interested in the interfaces I have created - I'm not after returning IEnumerable or ICloneable etc.) Or I could write helper methods for each interface. I was just wondering if there was a more elegant way of doing it?

like image 733
Orphid Avatar asked Jan 10 '23 07:01

Orphid


2 Answers

You can do it using generics:

private bool CheckType<T>(object o) {
    return o is T;
}

You call it like this:

foreach (object o in myList) {
    if (CheckType<MyInterface>(o)) {
        ... // Do something
    }
}

Considering how easy it is to do, you might as well do it in the conditional itself.

Finally, if you wish to process only objects implementing a particular interface in a mixed list, you could do it with LINQ's OfType method, like this:

foreach (MyInterface o in myList.OfType<MyInterface>()) {
   ...
}
like image 120
Sergey Kalinichenko Avatar answered Jan 20 '23 12:01

Sergey Kalinichenko


You can do something like:

private bool CheckType(object o, params Type[] types)
{
    //you can optionally check, that types are interfaces
    //and throw exceptions if non-interface type was passed
    if(types.Any(type => !type.IsInterface))
        throw new Exception("Expected types to have only interface definitions");

    return types.All(type => type.IsAssignableFrom(o.GetType()));
}


CheckType(new List<int>(), typeof(IEnumerable), typeof(IList)); //returns true
CheckType(0, typeof(IEnumerable)); //return false

To check a sequence of objects, you can use something along:

private bool CheckAllType(IEnumerable<object> items, params Type[] types)
{
    return items.All(item => CheckType(item, types));
}
like image 29
Ilya Ivanov Avatar answered Jan 20 '23 11:01

Ilya Ivanov