Search code examples
c#imagelockbits

C#, "?" and ":" operators


I not found any solution for my problem so i ask, how ? and : operators works when i have multiple statemants?

What i want to do, i have pixel on the middle pixel[pos] and pixels around, its look like:

0 0 0
0 x 0
0 0 0

x is a center pixel.

Im checking, if i have any white (zero) pixel around it. If is anyone, i marked pixel as two. If not, so pattern looks like:

1 1 1
1 x 1
1 1 1

1 is an black pixel, i set it to one.

Now, the code:

if(pixels[positionOfPixel] == one && x > 0 && x < width 
                                  && y > 0 && y < height)
{
    pixels[positionOfPixel] = pixels[positionOfPixel - 1]          == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel + 1]          == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset]     == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel + offset]     == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset + 1] == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel + offset - 1] == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset - 1] == zero ? two :
    pixels[positionOfPixel] = pixels[positionOfPixel - offset + 1] == zero ? two : zero;
}

My question is, why every one pixel is marked as two ? Why it didnt recognize pixel, where every pixel arond is one (like in second pattern)?

Thanks for any advices!


Solution

  • I'm not a C# specialist, but there is common rule how ? : operator can be used.

    x = (boolean condition) ? reult_if_true : result_if_false;
    

    E.g.

    drink = isThisPersonAGirl ? wine : beer;
    

    If you want to use many conditions with ? : operator, you should do it that way:

    x = (boolean condition 1) ? result_if_true : (boolean condition 2) ? result_if_bool_2_is_true : result_if false;
    

    E.g.

    drink = isThisPersonAChild ? lemonade : isThisPersonAGitl ? wine : beer
    

    In your code snippet, it's hard to understand what's going on because you use = operator too often. In most languages, you could initalize several variables like this:

    a = b = c = 0, so a, b, c will be = 0;

    So I think your mistake is using = operator too often so maybe only this condition does matter, while others are simply skipped:

    pixels[positionOfPixel - offset + 1] == zero ? two : zero;
    

    Sorry of it doesn't help, since I'm really not a C# coder)