-1

I have an embarrassingly simple C# question, but consider the following code:

using System;

namespace ConsoleApp3
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var valid = true;

            var something = Console.ReadLine();

            if (something == "Boom")
            {
                valid = false;
            }

            valid = DetermineSomethingElse();

            if (!valid)
            {
                return;
            }

            Console.WriteLine("Kerplamo");
        }

        private static bool DetermineSomethingElse()
        {
            var random = new Random();
            var next = random.Next(0, 5);

            return next == 3;
        }
    }
}

ReSharper claims that the valid assignment in:

if (something == "Boom")
{
    valid = false;
}

Isn't used, and that I can safely remove it, but I don't think this is accurate.

Am I missing something blatantly obvious, or is ReSharper making an error analyzing my code?

Edit: Nevermind, I'm an idiot!

Thanks

JMK
  • 27,273
  • 52
  • 163
  • 280
  • https://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same Maybe this will help you. – freshp Aug 16 '17 at 18:47
  • @freshp What does that have to do with this? – Servy Aug 16 '17 at 18:50
  • [MCVE] is still good guidance :) – Alexei Levenkov Aug 16 '17 at 19:12
  • The reason is because right after that you assign the return value of `DetermineSomethingElse()` to `valid`, which means any previous assignment is thrown away. In fact, your whole `Main` method can be condensed to: `private static void Main() { if (DetermineSomethingElse() Console.WriteLine("Kerplamo"); }` – Rufus L Aug 16 '17 at 19:53

3 Answers3

1

Because you're re-assigning it no matter what. You're assigning it here:

 if (something == "Boom")
 {
     valid = false;
 }

and re-assigning it here without using it before:

valid = DetermineSomethingElse();
Bruno Avelar
  • 670
  • 4
  • 16
  • I'm trying to figure out if two things are true at the same time. So if valid stays false, I don't want to do anything. – JMK Aug 16 '17 at 18:47
  • 3
    @JMK Your current code isn't doing that. It's checking if one thing is true, then ignoring that result and doing nothing with that boolean value, then it's determining if something else is true, and based *entirely* on whether that other thing is true or not it's doing something. – Servy Aug 16 '17 at 18:49
0

ReSharper is right. You do not access valid after assigning value. Try this code

if (something == "Boom")
{
    valid = false;
}
valid = valid && DetermineSomethingElse();
Aleks Andreev
  • 7,016
  • 8
  • 29
  • 37
0

You are overwriting the var valid immediately. The whole if-block can either be removed or you have to fix the line below (for example like Aleks shows you).

iquellis
  • 979
  • 1
  • 8
  • 26