Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

What is the difference between & and && operators in C#

I am trying to understand the difference between & and &&operators in C#. I searched on the internet without success. Can somebody please explain with an example?

question from:https://stackoverflow.com/questions/4163483/what-is-the-difference-between-and-operators-in-c-sharp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

& is the bitwise AND operator. For operands of integer types, it'll calculate the bitwise-AND of the operands and the result will be an integer type. For boolean operands, it'll compute the logical-and of operands. && is the logical AND operator and doesn't work on integer types. For boolean types, where both of them can be applied, the difference is in the "short-circuiting" property of &&. If the first operand of && evaluates to false, the second is not evaluated at all. This is not the case for &:

 bool f() {
    Console.WriteLine("f called");
    return false;
 }
 bool g() {
    Console.WriteLine("g called");
    return false;
 }
 static void Main() {
    bool result = f() && g(); // prints "f called"
    Console.WriteLine("------");
    result = f() & g(); // prints "f called" and "g called"
 }

|| is similar to && in this property; it'll only evaluate the second operand if the first evaluates to false.

Of course, user defined types can overload these operators making them do anything they want.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...