본문 바로가기

Etc/C#

& 과 &&의 차이


// cs_operator_logical_and.cs
using System;
class MainClass
{
   static bool Method1()
   {
      Console.WriteLine("Method1 called");
      return false;
   }

   static bool Method2()
   {
      Console.WriteLine("Method2 called");
      return true;
   }

   static void Main()
   {
      Console.WriteLine("regular AND:");
      Console.WriteLine("result is {0}", Method1() & Method2());
      Console.WriteLine("short-circuit AND:");
      Console.WriteLine("result is {0}", Method1() && Method2());
   }
}

결과
regular AND:
Method1 called
Method2 called
result is False
short-circuit AND:
Method1 called
result is False

보시는것처럼 &는 앞에 값에 상관 없이 뒤의 항목에까지 가구용
&&는 앞에값이 False이면 뒤의 항목까지 안가는군용!!

|| 도 같은식으로 사용이 가능합니다 :-0