Boolean Type and Operators - CSharp Language Basics

CSharp examples for Language Basics:boolean

Introduction

C#'s bool type (aliasing the System.Boolean type) is a logical value that can be assigned the literal true or false.

Demo Code

using System;/*from   www  .  j  ava  2 s.c  o m*/
class Test
{
   static void Main(){
      int x = 1;
      int y = 2;
      int z = 1;
      Console.WriteLine (x == y);         // False
      Console.WriteLine (x == z);         // True
   }
}

Result

For reference types, equality, by default, is based on reference, as opposed to the actual value of the underlying object (more on this in Chapter 6):

Demo Code

using System;//from  w  ww .  j  av a 2s. c  o m
     public class Dude
     {
       public string Name;
       public Dude (string n) { Name = n; }
     }
class Test
{
static void Main(){
     Dude d1 = new Dude ("John");
     Dude d2 = new Dude ("John");
     Console.WriteLine (d1 == d2);       // False
     Dude d3 = d1;
     Console.WriteLine (d1 == d3);       // True

}
}

Result


Related Tutorials