ReSharper: if/else if vs switch in C#
c#, refactoring, resharper
Solution
Your example is a very specific case where you are running an if statement within a not thread safe loop, meaning you expect another task to change the value of a variable while evaluating it.
Usually you want to prevent such cases because this can lead to very bad issues.
And regarding your question, how should ReSharper know about this fact? Usually, if you do an if/elseif, we can expect that the statement gets evaluated correctly right?
In addition, the switch even helps you prevent this kind of mess, so in my opinion, R# is right ;)
But of course, you can not trust R# blindly without double checking the suggestions. Often some suggestions are crap and you also have to configure R# to match with your code style guidelines etc... It's just a tool ;)
Problem
So I was discussing with a colleague the benefits of ReSharper (currently v8.1) in terms of refactoring if/else if statements to switch statements. I had not given this much thought but my colleague came up with the example below. The thing is that when the code is run you can see that it actually gets to "else" statement in the DoElseIf but not in the DoSwitch. Even so ReSharper suggests that I refactor my if/else if to a switch statement when it's obvious that the compiled code does not behave the same way. Can anyone with more knowledge of ReSharper than me tell me if I'm looking at this the wrong way or if I should be careful refactoring an if/else if to a switch statement? Here's the code: ``` namespace ConsoleApplication1 { class Program { static bool MyValue { get; set; } static void Main(string[] args) { Task t = new Task(ChangeIt); t.Start(); for (var i = 0; i < 1000000; i++) { DoElseIf(); } for (var i = 0; i < 1000000; i++) { DoSwitch(); } Console.WriteLine("Work's done!"); Console.ReadLine(); } static void DoSwitch() { switch (MyValue) { case true: //Console.WriteLine("true"); break; case false: //Console.WriteLine("false"); break; default: Console.WriteLine("WTF (Switch)!"); break; } } static void DoElseIf() { if (MyValue == true) { //Console.WriteLine("true"); } else if (MyValue == false) { //Console.WriteLine("false"); } else { Console.WriteLine("WTF (Else-if)!"); } } public static void ChangeIt() { MyValue = !MyValue; Task.Factory.StartNew(ChangeIt); } } } ``` Thanks in advance and happy holidays to all :-)