36

Possible Duplicate:
What are the | and ^ operators used for?

In c# what does the ^ character do?

Community
  • 1
  • 1
arkina
  • 991
  • 2
  • 11
  • 17
  • 35
    An additional usage of "^" in C#, or which at least appears throughout .NET documentation without any explanation, is the "handle to object operator." This is a C++ thing that marks an object for garbage collection so you don't have to worry about memory mgt yourself. It's all over MSDN .NET docs e.g. `SomeMethod(String^, IDictionary^)`, but is not actually explained anywhere. The only thing that comes up in Google or SE regarding "^" in C# is this answer of "XOR", which is completely different. https://msdn.microsoft.com/en-us/library/yk97tc08.aspx – mc01 May 09 '17 at 20:21
  • See also [what-does-the-caret-mean-in-c-cli](https://stackoverflow.com/questions/202463/what-does-the-caret-mean-in-c-cli) – kca Mar 28 '23 at 11:42

4 Answers4

37

This is binary XOR operator.

Binary ^ operators are predefined for the integral types and bool. For integral types, ^ computes the bitwise exclusive-OR of its operands. For bool operands, ^ computes the logical exclusive-or of its operands; that is, the result is true if and only if exactly one of its operands is true.

Oleks
  • 31,955
  • 11
  • 77
  • 132
8

The ^ charater, or 'caret' character is a bitwise XOR operator. e.g.

using System;

class Program
{
    static void Main()
    {
        // Demonstrate XOR for two integers.
        int a = 5550 ^ 800;
        Console.WriteLine(GetIntBinaryString(5550));
        Console.WriteLine(GetIntBinaryString(800));
        Console.WriteLine(GetIntBinaryString(a));
        Console.WriteLine();

        // Repeat.
        int b = 100 ^ 33;
        Console.WriteLine(GetIntBinaryString(100));
        Console.WriteLine(GetIntBinaryString(33));
        Console.WriteLine(GetIntBinaryString(b));
    }

    /// <summary>
    /// Returns binary representation string.
    /// </summary>
    static string GetIntBinaryString(int n)
    {
        char[] b = new char[32];
        int pos = 31;
        int i = 0;

        while (i < 32)
        {
            if ((n & (1 << i)) != 0)
            {
                b[pos] = '1';
            }
            else
            {
                b[pos] = '0';
            }
            pos--;
            i++;
        }
        return new string(b);
    }
}

^^^ Output of the program ^^^

00000000000000000001010110101110
00000000000000000000001100100000
00000000000000000001011010001110

00000000000000000000000001100100
00000000000000000000000000100001
00000000000000000000000001000101

http://www.dotnetperls.com/xor

Ken Y-N
  • 14,644
  • 21
  • 71
  • 114
George Duckett
  • 31,770
  • 9
  • 95
  • 162
2

Take a look at MSDN ^ Operator (C# Reference)

Kalman Speier
  • 1,937
  • 13
  • 18
0

It's the logical XOR operator.

Jeff Hubbard
  • 9,822
  • 3
  • 30
  • 28