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.

see

http://msdn.microsoft.com/de-de/library/wcxyzt4d(v=vs.80).aspx

c# generics .net-3.5

Comments

Popular posts from this blog

How do I check if an insert was successful with MySQLdb in Python? -

delphi - blogger via idHTTP : error 400 bad request -

postgresql - ERROR: operator is not unique: unknown + unknown -