c# - Accesing a Class.Name property from diffrent classes without inheritance -
i trying write method uses name property of diffrent classes , logic it.
in exampel keep simple restrict myself returning name value:
class dog { public string name { get; set; } } class human { public string name { get; set; } } /* ... */ public string getnamefromnameproperty(object obj) { return obj.name; } sadly classes not inherting parent class has name property. furthermore not possible implement or add interface.
short recap:
possible write generic method uses name property without being sure class has implemented property?
if really don't want make classes implement common interface or inherit base class, here 2 options:
reflection:
public string getnamefromnameproperty(object obj) { var type = obj.gettype(); return type.getproperty("name").getvalue(obj) string; } dynamic binding:
public string getnamefromnameproperty(dynamic obj) { try { return obj.name; } catch (runtimebinderexception) { throw new propertydoesntexistexception(); } } you can choose return null if property not exist.
however, advise use interfaces or inheritance this. lose type-safety c# provides if used above methods.
Comments
Post a Comment