String casting in IEnumerable <object>

I have propertyValuewhich is the object passed to my function.

I can assume that this is some kind IEnumerable, however, due to the interface contract, I have to accept it as object, rather than directly as IEnumerable.

When I try to pass my value in IEnumerable<object>, so that I can get the length I get InvalidCastException.

var length = ((IEnumerable<object>) propertyValue).Cast<object>().Count();

I get the following exception:

System.InvalidCastException: It is not possible to list an object of type 'System.String' to enter type 'System.Collections.Generic.IEnumerable`1 [System.Object]'.

+4
source share
4

, IEnumerable, IEnumerable<object>.

var length = ((IEnumerable) propertyValue).Cast<object>().Count();
+2

IEnumerable<T> , . - , . - , .

string IEnumerable<char>, IEnumerable<object>.

, , - IEnumerable.

var length = ((IEnumerable) propertyValue).Cast<object>().Count();
+7

String IEnumerable<char>,

var length = ((IEnumerable<char>) propertyValue).Count();

IEnumerable .

static class EnumerableExtensions
{
    public static int Count(this IEnumerable source)
    {
        int res = 0;

        foreach (var item in source)
            res++;

        return res;
    }
}

var collection = propertyValue as IEnumerable;
if(collection != null)
{
    var length = collection.Count();
}

Using the Cast () method will result in value type boxes and may have performance issues for large collections.

+1
source

The following code should really do what you need

var length = (propertyValue as IEnumerable<object>).Count();      
0
source

Source: https://habr.com/ru/post/1621281/


All Articles