Eugene Marin
Eugene Marin

Reputation: 1796

Casting to a generic of any type in C#

I have an object value that might represent objects of different types (string, enums, List etc). What I want to do is check whether the variable is an empty list, like this:

(value is List<object> && ((List<object>)value).Count == 0)

or

(value is List<dynamic> && ((List<dynamic>)value).Count == 0)

But with real empty lists both return false.
I'd like to know what's the best way to do this, and if there's something like Java's List<?> in C#.

Upvotes: 1

Views: 114

Answers (2)

šljaker
šljaker

Reputation: 7374

You can create a helper class:

public static class CollectionHelpers
{
    public static bool IsNullOrEmpty(this ICollection collection)
    {
        return collection == null || collection.Count == 0;
    }
}

And use it like this:

class Program
{
    static void Main(string[] args)
    {
        object list = new List<int> { 1, 2, 3 };
        Console.WriteLine((list as ICollection).IsNullOrEmpty());
    }
}

or

class Program
{
    static void Main(string[] args)
    {
        var list = new List<int>();
        Console.WriteLine(list.IsNullOrEmpty());
    }
}

Upvotes: 0

Selman Gen&#231;
Selman Gen&#231;

Reputation: 101731

You can cast it to IList

if( (value as IList).Count == 0 )

If you are not sure whether the value implements IList, it is better to check for null:

var list = value as IList;
if(list != null && list.Count == 0)

Upvotes: 3

Related Questions