Create a new object based on a type parameter

I am trying to throw an exception based on an exception type parameter passed to the method.

Here is what I have, but I do not want to indicate each kind of exception:

public void ThrowException<T>(string message = "") where T : SystemException, new() { if (ConditionMet) { if(typeof(T) is NullReferenceException) throw new NullReferenceException(message); if (typeof(T) is FileNotFoundException) throw new FileNotFoundException(message); throw new SystemException(message); } } 

Ideally, I want to do something like new T(message) , given that I have a basic SystemException type. I would think that this is possible.

+4
source share
3 answers

I do not think that you can do this using only geriki. You will need to use reflection. Sort of:

 throw (T)Activator.CreateInstance(typeof(T),message); 
+6
source

As others have argued, this can only be done with reflection. But you can remove the type parameter and pass the generated exception to the function:

 public void ThrowException(Exception e) { if (ConditionMet) { if(e is NullReferenceException || e is FileNotFoundException) { throw e; } throw new SystemException(e.Message); } } 

Using:

 // throws a NullReferenceException ThrowException(new NullReferenceException("message")); // throws a SystemException ThrowException(new NotSupportedException("message")); 
+1
source

you can use

 Activator.CreateInstance(typeof(T),message); 

More details at http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx

0
source

Source: https://habr.com/ru/post/1381641/


All Articles