0

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?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
csc
  • 607
  • 1
  • 4
  • 15
  • What is the *actual* type involved here? Most collections implement the nongeneric `ICollection` interface as well, which makes things simpler... could you use that instead? – Jon Skeet Jan 05 '14 at 17:27
  • 1
    You could also use `IEnumerable`. This is where `Count()` is declared. – Nico Schertler Jan 05 '14 at 17:29
  • The actual Type of the list is **List** and it is working with the ICollection interface casting! Sorry, I am new to c# ... – csc Jan 05 '14 at 17:43

1 Answers1

1

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.

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185