Whenever I see those if else if sentences, I find it easier to do this. In some cases, the switch statement may help, but as this question has already been pointed out, it is not possible to include Type.
So another workaround that I usually use is a kind of Dictionary<Type, something> . Where something depends on what I would like to do. Perhaps a suitable construct for your case will be similar to Dictionary<Type, Func<Exception, string>> , which can be used in your case something like this:
Dictionary<Type, Func<Exception, string>> _FunctorsForType; private void InitializeFunctorsForType() { _FunctorsForType = new Dictionary<Type, Func<Exception, string>>(); // Add a normal function _FunctorsForType.Add(typeof(ArgumentException), (Func<Exception, string>)ForArgumentException); // Add as lambda _FunctorsForType.Add(typeof(InvalidCastException), (ex) => { // ToDo: Whatever you like return ex.Message; }); } private string ForArgumentException(Exception ex) { var argumentException = ex as ArgumentException; if (argumentException == null) { throw new ArgumentException("Exception must be of type " + typeof(ArgumentException).Name); } // ToDo: Whatever you like return ex.Message; } private void Usage(Type type) { Func<Exception, string> func; if (!_FunctorsForType.TryGetValue(type, out func)) { throw new ArgumentOutOfRangeException("Exception type " + type.Name + " is not supported."); } var message = func(new NullReferenceException()); // ToDo: Whatever you have to do with your message }
Thus, with this design, you do not need to inject all your intelligence into a large if-else statement. Instead, you can put them in separate functions (possibly in different classes) to get a better organization of how to handle each type that you like to support.
source share