Natalie Perret
Natalie Perret

Reputation: 9037

Is there a handy way to figure out whether an Object implements

I'm trying to figure out if there is any builtin routines or classes in the .NET framework that could provide a convenient way to test whether a collection implements among the following interfaces and hence hook to the relevant events, if any:

Mostly for data-binding purposes...

I can go with a lot of reflections (e.g. IsAssignableFrom) but since it seems to be a pretty common scenario, I was wondering if there was anything already done in that regard.

[EDIT]
Seems my question is too vague or poorly phrased, my bad. As I indicated a bit later in one of my comments I was more looking for a way to provide a centralized databinding way of doing, could be interested to make UI-agnostic, seems MS provides internally some tooling such as: http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DataGridViewDataConnection.cs,68950bc360ed4e45,references but nothing is public.

Right now, my approach is to wrap up everything with a kind of BindingSource equivalent and check whether the object passed to the constructor implements any of the interface I am willing to hook up with.

Upvotes: 1

Views: 85

Answers (4)

Didier Aupest
Didier Aupest

Reputation: 3377

I guess you should create your own extension method:

public static class CustomCollectionExtension
{
    public static bool AddEvent(this IList myList, EventHandler e)
    {
        // Do Some Stuff
        return true;
    }

    public static bool AddEvent(this ICollection myCollection, EventHandler e)
    {
        // Do Some Stuff
        return true;
    }

    // And so on...

}

Then, in your application it will be easy to use it, without knowing the type of your collection with something like:

dataContainer.AddEvent(evt);

Upvotes: 0

Thomas Voß
Thomas Voß

Reputation: 1165

You could alternatively to the is operator of the previous answer use the as Operator:

var IEnumerable myIEnumerableObject = unknownObject as IEnumerable;
if(myIEnumerableObject != null)
{
    myIEnumerableObject.SomeEvent += SomeEventHandler;
}

Upvotes: 2

Owuor
Owuor

Reputation: 616

You can check for the specific interface from the collection e.g.

if(CurrentCollection.GetType().GetInterface("IInterfaceName")!=null)
{
   // Implements interface IInterfaceName
}

Upvotes: 0

Dan Forbes
Dan Forbes

Reputation: 2824

As mentioned by @aquinas, you can use the .Net is keyword to check whether or not an instance of an object implements a specified interface.

Example:

if (unknownObject is IEnumerable)
{
    foreach (var obj in uknownObject)
    {
        Console.WriteLine(obj.ToString());
    }
}

Upvotes: 0

Related Questions