Question

I want to create a type independent Converter for counting the elements in a collection with a generic type.

    public class CollectionCountConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return ((SomeCastingType)value).Count;
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException(); // not used for oneway binding
    }
}

value in this case is a Collection of any type. The problem is to find the correct casting type and cast the object. What I want to have is something like

Type t = value.GetType();
ICollection<t> c = (ICollection<t>) value;
int count = c.Count();

but this does not work. I also tried to use Object as generic type, but then I get an InvalidCastException. Is there any elegant way to do it?

Was it helpful?

Solution

Since IEnumerable<T> is covariant, you can use this.

return ((System.Collections.Generic.IEnumerable<object>)value).Count();

From MSDN:

Type Parameters

out T

The type of objects to enumerate.

This type parameter is covariant. That is, you can use either the type you specified or any type that is more derived.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top