c# - Generic Type Exceptions -
c# - Generic Type Exceptions -
recently came across problem of creating exception given message within generic method. instance, next code works expected:
public static void throw<t>() t : exception, new() { throw new t(); } ... public static void main() { throw<argumentoutofrangeexception>(); // throws desired exception generic message. }
however, able write
public static void throw<t>(string message) t : exception, new() { t newexception = new t(); newexception.message = message; // not allowed. 'message' read-only. throw newexception; } ... public static void main() { throw<argumentoutofrangeexception>("you must specify non-negative integer."); // throws desired exception. }
is there way of achieving without utilize of reflection either alter value of message
property or dinamically activate instance of type desired parameters?
you can utilize activator.createinstance(typeof(t), "myexception description")
enable custom message.
there no way create instance without utilize of reflection or utilize of activator.
seehttp://msdn.microsoft.com/de-de/library/wcxyzt4d(v=vs.80).aspx
c# generics .net-3.5
Comments
Post a Comment