You should always write your code to avoid exceptions. They are very expensive to catch.
You should also avoid many nested if . You are right, they make your code less readable.
You may find that switch can help, but there are a number of other ways to avoid exceptions and if .
For example, you can write this extension method:
public static class Ex { public static void IfBounded<T>(this T[] @this, int index, Action<T> action) { if (@this == null) throw new System.ArgumentNullException("@this"); if (action == null) throw new System.ArgumentNullException("action"); if (index >= @this.GetLowerBound(0) && index <= @this.GetUpperBound(0)) { action(@this[index]); } } }
Now you can write the following code:
var messages = new [] { "Hello", "Goodbye", }; messages.IfBounded(-1, t => Console.WriteLine(t)); messages.IfBounded(0, t => Console.WriteLine(t)); messages.IfBounded(1, t => Console.WriteLine(t)); messages.IfBounded(2, t => Console.WriteLine(t));
This particular extension method may not be suitable for your situation, but something like this can make your code quite concise and concise.
source share