C# instantiate generic type from method signature -
i've been fooling around generic methods lately , came across methods this:
public static void requires<texception>(bool condition, string message) texception : exception to understanding, when using above method provide type inherits exception , if condition false provided exception type thrown.
how work under hood?
texception instantiated throw new texception();?
, how can pass in message parameter if type unknown method (all knows inherits type exception)?
according msdn : system.exception have constructor takes string argument. string represents message.
with of activator-class can following pretty simple:
using system; public class test { public static void requires<texception>(bool condition, string message) texception : exception { exception exception = (exception)activator.createinstance(typeof(texception),message); throw exception; } public static void main() { try { requires<argumentnullexception>(true,"test"); } catch(exception e) { console.writeline(e); } } } working example: http://ideone.com/behyuo
Comments
Post a Comment