c# - How to access inherited values -


i have method exception variable parameter. exception can inherit other values custom exceptions, apart default values, , wondering how access these custom values without casting custom exception object or verifying hresult (this same due how method's arguments).

for example, in cases exception object can inherit list, can't access list. method return right value must first find way identify exception , accessing inherited values, i'll able to.

this i've tried far:

-exception handling method-

private string exceptionhandler(exception ex) {     var customexceptionmessages = string.empty;      //i want avoid     var customexception = ex customexception;      if (customexception != null)     {         //build custom exception message         foreach (var v in customexception.customviolations)         {             customexceptionmessages += v.errormessage + "<br />";         }          return customexceptionmessages;     }      else         return ex.message; } 

-example of usage-

exceptionhandler(customex); 

after debugging, noticed before exceptionhandler runs, customex has user defined values. after exceptionhandler starts running, ex inherits default values of exception plus custom ones. can't ex.customviolations cause exists on run time.

usually achieve kind of thing using visitor pattern. however, here can't modify exception's source code. fortunately, in c# have dynamic keyword allows this:

private string exceptionhandler(concreteexception1 ex) //... private string exceptionhandler(concreteexception2 ex) //... private string exceptionhandler(exception ex) // default  x.exceptionhanlder((dynamic)ex); // call appropriate overload 

of course, under hood type check internally, solution scalable - thing need add overload each new exception type.


another approach in such cases when don't have/don't want dynamic type use dictionary of concrete handlers each exception:

dictionary<type, exceptionhandler> handlers = ...  handlers[ex.gettype()].handle(ex); 

(in example, i've changed exceptionhandler class name, , use handle method name - preferred, less confusing way name methods , types ;) )

you can involve generic method magic avoid casting inside handle method, without this, don't have check invalid casts.


Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -