A clear, layman's explanation of the difference between | and || in c#?

后端 未结 11 534
余生分开走
余生分开走 2020-12-02 12:51

Ok, so I\'ve read about this a number of times, but I\'m yet to hear a clear, easy to understand (and memorable) way to learn the difference between:

if (x |         


        
11条回答
  •  失恋的感觉
    2020-12-02 13:31

    Although it's already been said and answered correctly I thought I'd add a real layman's answer since alot of the time that's what I feel like on this site :). Plus I'll add the example of & vs. && since it's the same concept

    | vs ||

    Basically you tend to use the || when you only wnat to evaluate the second part IF the first part it FALSE. So this:

    if (func1() || func2()) {func3();}
    

    is the same as

    if (func1())
    {
        func3();
    }
    else 
    {
        if (func2()) {func3();}
    }
    

    This may be a way to save processing time. If func2() took a long time to process, you wouldn't want to do it if func1() was already true.

    & vs &&

    In the case of & vs. && it's a similar situation where you only evaluate the second part IF the first part is TRUE. For example this:

    if (func1() && func2()) {func3();}
    

    is the same as

    if (func1())
    {
        if (func2()) {func3();}}
    }
    

    This can be necessary since func2() may depend on func1() first being true. If you used & and func1() evaluated to false, & would run func2() anyways, which could cause a runtime error.

    Jeff the Layman

提交回复
热议问题