I have an object.
This object is casting an Items Container (I don’t know what items, but I can check).
But is there any code which can help me find how many items it contains?
I mean
object[] arrObj = new object[2] {1, 2};
object o = (object)arrObj;
In this case arrObj is an array so I can check:
((Array)o).Length //2
But what if I have those 2 others ?
ArrayList al = new ArrayList(2);
al.Add(1);
al.Add(2);
object o = (object)al ;
and
List<object> lst= new List<object>(2);
object o = (object)lst;
Is there any general code which can help me find how many items are in this casted object (o in this samples) ?
Of course I can check if (o is ...) { } but Im looking for more general code.
Well the most basic interface it could implement would be
IEnumerable. Unfortunately evenEnumerable.Countfrom LINQ is implemented forIEnumerable<T>, but you could easily write your own:Note that this is basically equivalent to:
… except that because it never uses
Current, it wouldn’t need to do any boxing if your container was actually anint[]for example.Call it with:
It’s worth noting that avoiding boxing really is a bit of a micro-optimization: it’s unlikely to really be significant. But you can do it once, just in this method, and then take advantage of it everywhere.