views:

331

answers:

4

Hi

I have this if statement -

if (!((main.property == 1)||(main.property == 2)))
{
   ...
}

main.property is a byte which is either 0, 1, 2 or 98.

Visual studios says that this statement is always true but I can't see why?

If the property is 1 or 2 shouldn't this be false.

Thank you in advance.

Edit: Added code

file1.cs

private void Upload(DataSet ds)
{
    Main main = CreateMain(ds); //This is tested and works correctly
    if(ValidateDate(main))
    {
        ...
    }
}

file2.cs

internal static bool ValidateData(Main main, ...)
{
    if (!((main.property == 1)||(main.property == 2)))
    {
        ...
    }
}

Edit: Added code

If I do this the error goes away -

internal static bool ValidateData(Main main, ...)
{
     main.property = 0; //Or = any number
     if (!((main.property == 1)||(main.property == 2)))
     {
          ...
     }
}

I'm guessing VS thinks it isn't initialised but I am 100% positive it is.

+2  A: 

I wrote this little program to check it out:

    class Program
{
    static void Main(string[] args)
    {
        test(0);
        test(1);
        test(2);
        test(3);
        Console.ReadLine();
    }

    private static void test(int p)
    {
        bool b1 = (!((p == 1) || (p == 2)));
        bool b2 = (p != 1 && p != 2);
        Console.Out.WriteLine("{0} {1} {2}", b1, b2, b1 == b2);
    }
}

It seems that Constantin is right in his transcription, but neither expression is always true or always false.

Guge
who is Constantin?
fearofawhackplanet
@fearof - The author of a now deleted answer on this question.
Martin Smith
+1  A: 
stakx
A: 

Step through your code to find out what main.property value is.

I had a similar issue and it was because the value was null the default value.

Webicus
Main would apear to be an int, which is not nullable.
Ben Robinson
According to the OP its a byte.Which can't be null.Thinking of byte arrays. Fail.Clarifying post.
Webicus
I hope bytes can be null. Doesn't byte? mean it's nullable.
Ash Burlaczenko
A C# byte is an integral value type and value types cannot contain the null value: http://msdn.microsoft.com/en-us/library/s1ax56ch.aspx ."byte?" is a nullable type but is not exactly the same as a "byte" type http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx
Webicus
A: 

Since you claim that main.property is a byte which is either 0, 1, 2 or 98, you should assert that condition at the beginning of that method as such:

internal static bool ValidateData(Main main, ...)
{
    System.Diagnostics.Debug.Assert(main.property == 0 || main.property == 1 || main.property ==2 || main.property == 98);
    if (!((main.property == 1)||(main.property == 2)))
    {
        ...
    }
}
Jesse C. Slicer