C# object runtime type casting -


i have variable (i'll call prop) type "object", know underlying type sort of icollection. i'd iterate collection , tostring elements.

my prop variable has method gettype() returns type.

foreach (var item in prop icollection<pcnweb.models.port>) {     //do more cool stuff here } 

the problem being don't know inner type of icollection @ compiletime, (listed above pcnweb.models.port).

calling prop.gettype().tostring() (in case) yields system.collections.generic.hashset`1[pcnweb.models.port]

i can tell information there need, not sure how make work.

i've tried number of things (albeit maybe incorrectly):

try 1:

type t = prop.gettype(); foreach (var item in convert.changetype(prop, t)) {     //do more cool stuff here } 

which yields:

compiler error message: cs1579: foreach statement cannot operate on variables of type 'object' because 'object' not contain public definition 'getenumerator' 

try 2:

type t = prop.gettype(); foreach (var item in prop t) {       //do more cool stuff here } 

which yields:

compiler error message: cs0246: type or namespace name 't' not found (are missing using directive or assembly reference?) 

try 3: (per @darkfalcon's suggestion)

type t = prop.gettype(); foreach (var item in prop icollection) {       //do more cool stuff here } 

which yields:

compiler error message: cs0305: using generic type 'system.collections.generic.icollection<t>' requires 1 type arguments 

foreach (var item in prop system.collections.ienumerable) {  } 

that should work. think you're getting tripped having using system.collections.generic; in code file (so thinks want system.collections.generic.ienumerable<t> instead of system.collections.ienumerable)

if go @ the documentation foreach you'll see @ top:

the foreach statement repeats group of embedded statements each element in array or object collection implements system.collections.ienumerable or system.collections.generic.ienumerable<t>

so have prop referenced 1 of 2 types. since don't know t, should go non-generic one.


Comments

Popular posts from this blog

How to mention the localhost in android -

php - Calling a template part from a post -

c# - String.format() DateTime With Arabic culture -