c# - Method to handle objects with properties in common, but different object types -


i have large collection of automatically generated objects. although of different, non-related classes, of objects share basic properties (name, id, etc.). i not control generation of these objects, unfortunately cannot take ideal approach of implementing interface. create method in pass arbitrary 1 of these objects , using these common properties.

the general idea like:

someobj = new someobj(); a.name = "sara"; diffobj b = new diffobj(); b.name = "joe"; string phrase = string.format("i {0} , {1}",      getname(a), getname(b));  private string getname(object anyobjwithname) {     return anyobjwithname.name; } 

though naturally not work.

i thought generic method might hold answer, way can see call current type using genericmethod.invoke , still carries same issue of not being able resolve properties of passed object in method. unlike calling generic method type argument known @ execution time or how call generic method given type object? type, or properties of type, used in method, opposed properties of object.

i aware (very) prone error, can guarantee objects encountered have common properties being manipulated.

i can guarantee objects encountered have common properties being manipulated

if that's case, can use dynamic:

private string getname(dynamic anyobjwithname) {     return anyobjwithname.name; } 

be aware using object not have name property not fail until run-time.

if want add little bit of safety can catch runtimebinderexception gets thrown if property not exist:

private string getname(dynamic anyobjwithname) {     try {         return anyobjwithname.name;     }     catch(runtimebinderexception) {         return "{unknown}";     } } 

Comments

Popular posts from this blog

ios - UICollectionView Self Sizing Cells with Auto Layout -

node.js - ldapjs - write after end error -

DOM Manipulation in Wordpress (and elsewhere) using php -