Export (0) Print
Expand All

!= Operator

The inequality operator (!=) returns false if its operands are equal, true otherwise. Inequality operators are predefined for all types, including string and object. User-defined types can overload the != operator.

expr1 != expr2

Where:

expr1
An expression.
expr2
An expression.

Remarks

For predefined value types, the inequality operator (!=) returns true if the values of its operands are different, false otherwise. For reference types other than string, != returns true if its two operands refer to different objects. For the string type, != compares the values of the strings.

User-defined value types can overload the != operator (see operator). So can user-defined reference types, although by default != behaves as described above for both predefined and user-defined reference types. If != is overloaded, == must also be overloaded.

Example

// cs_operator_inequality.cs
using System;
class Test 
{
   public static void Main() 
   {
      // Numeric inequality:
      Console.WriteLine((2 + 2) != 4);
   
      // Reference equality: two objects, same boxed value
      object s = 1;
      object t = 1;
      Console.WriteLine(s != t);

      // String equality: same string value, same string objects
      string a = "hello";
      string b = "hello";

      // compare string values
      Console.WriteLine(a != b);
   
      // compare string references
      Console.WriteLine((object)a != (object)b);
   }
}

Output

False
True
False
False

See Also

C# Operators | 7.9 Relational and type testing operators | == Operator

Show:
© 2014 Microsoft