Simon
Simon

Reputation: 8347

How can I check the type of an object when adding objects to a Collection<T>?

I have a question about adding an object to a Collection<T> from an inherited class.

Here is some example base class code:

public virtual Collection<CustomProperty> customProperties
{
    get
    {
        return _customProperties;
    }
    set
    {
        _customProperties = value;
    }
}

Here is some example inherited class code:

public override Collection<CustomProperty> customProperties
{
    get
    {
        return base.customProperties;
    }
    set
    {
        base.customProperties = value;
    }
}

In the above code, when adding objects that inherit from CustomProperty, how is the best way to check if the object is of a certain type, and then call a function if the object is of the certain type?

I can write a function that inherits from Collection<CustomProperty> and override the protected virtual void InsertItem(int index, T item) function, but would like to know if there is another way.

Upvotes: 0

Views: 109

Answers (1)

AlgorithmsAreCool
AlgorithmsAreCool

Reputation: 195

Collection<T> is an extensible wrapper around List<T>. Inheriting from it and overriding InsertItem is the exact way to control that sort of thing.

Is there a reason you need another way?

Here is a little helper i have used in my toolkit many times.

class FilteringCollection<T> : Collection<T>
{
    private readonly Func<T, bool> Filter;
    FilteringCollection(Func<T, bool> filter)
    {
        Filter = filter;
    }

    protected override InsertItem(int index, T item)
    {
        if(Filter(item))
             base.InsertItem(index, item);
        else
           ;//either ignore or throw an exception here
    }
}

//Or perhaps
class TypeSensitiveCollection<T, TSpecial> : Collection<T>
    where TSpecial : T
{
    public event EventHandler<TSpecial> SpecialMemberAdded;

    TypeSensitiveCollection()
    {

    }

    protected override InsertItem(int index, T item)
    {
        if(item is TSpecial)
        {
             if(SpecialMemberAdded != null)
                 SpecialMemberAdded(this, item as TSpecial)
        }
        base.InsertItem(index, item);
    }
}

Upvotes: 1

Related Questions