Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell whether a Type is a list or array or IEnumerable or

Tags:

c#

reflection

What's the easiest way, given a Type object, to test to see whether it is actually a list of objects? I.e. Array or IEnumerable/IEnumerable<>.

like image 750
Neil Barnwell Avatar asked Nov 07 '10 00:11

Neil Barnwell


People also ask

How to check is List or array in c#?

Given an object or an IList<T>, you can use the following code to check whether the object is an array. IList<string> someIds = new string[0]; if (someIds is Array) { // yes! } IList<string> someIds = new List<string>(0); if (someIds is Array) { // nop! }

Is IEnumerable an array?

IEnumerable is a behavior while Array is a data structure(Contiguous collection of elements with fixed size, facilitating accessing elements by indexes) .

Which is faster List or IEnumerable?

IEnumerable is conceptually faster than List because of the deferred execution. Deferred execution makes IEnumerable faster because it only gets the data when needed. Contrary to Lists having the data in-memory all the time.


1 Answers

Check typeof(IEnumerable).IsAssignableFrom(type).

Every collection type, including arrays and IEnumerable<T>, implements IEnumerable.

like image 165
SLaks Avatar answered Sep 18 '22 01:09

SLaks