JuninZe
JuninZe

Reputation: 79

The object is an Array or IEnumerable

I wonder if there is a way to find if the object is an array or IEnumerable, it was more beautiful than this:

var arrayFoo = new int[] { 1, 2, 3 };

var testArray = IsArray(arrayFoo);
// return true
var testArray2 = IsIEnumerable(arrayFoo);
// return false

var listFoo = new List<int> { 1, 2, 3 };

var testList = IsArray(listFoo);
// return false
var testList2 = IsIEnumerable(listFoo);
// return true


private bool IsArray(object obj)
{
    Type arrayType = obj.GetType().GetElementType();
    return arrayType != null;
}

private bool IsIEnumerable(object obj)
{
    Type ienumerableType = obj.GetType().GetGenericArguments().FirstOrDefault();
    return ienumerableType != null;
}

Upvotes: 1

Views: 863

Answers (2)

Pressacco
Pressacco

Reputation: 2875

Does this help?

"is" keyword

Checks if an object is compatible with a given type.

static void Test(object value)
{
    Class1 a;
    Class2 b;

    if (value is Class1)
    {
        Console.WriteLine("o is Class1");
        a = (Class1)o;
        // Do something with "a."
    } 
}

"as" keyword

Attempts to cast the value to a given type. If cast fails, null is returned.

Class1 b = value as Class1;
if (b != null)
{
   // do something with b
}

REFERENCE

"is" keyword

http://msdn.microsoft.com/en-us/library/scekt9xw(v=vs.110).aspx

"as" keyword

http://msdn.microsoft.com/en-us/library/cscsdfbt(v=vs.110).aspx

Upvotes: 5

Joe Enos
Joe Enos

Reputation: 40393

There's an is keyword in C#:

private bool IsArray(object obj)
{
    return obj is Array;
}

private bool IsIEnumerable(object obj)
{
    return obj is IEnumerable;
}

Upvotes: 7

Related Questions