Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ~ symbol in C# serves two distinct syntactical purposes depending on its context: as the unary bitwise complement operator and as the finalizer declaration syntax. 1. Bitwise Complement Operator As a unary operator, ~ performs a bitwise logical negation on integral numeric types and enumeration (enum) types. It evaluates the binary representation of the operand and inverts each bit, converting 0 to 1 and 1 to 0. Technical Mechanics:
  • The operator is natively defined for int, uint, long, ulong, nint, nuint, and all enum types.
  • When applied to smaller integral types (byte, sbyte, short, ushort), the operand undergoes implicit numeric promotion to int before the bitwise inversion occurs. The result evaluates to an int.
  • When applied to an enum type, the operation evaluates to the enum type itself. Unlike smaller integral types, applying ~ to an enum with a smaller underlying type (e.g., an enum backed by a byte or short) returns the enum type, not an int.
  • Because C# utilizes two’s complement representation for signed integers, applying ~ to a signed integer x mathematically yields -x - 1.
uint a = 0b_0000_1111_0000_1111_0000_1111_0000_1111;
uint b = ~a;
// b evaluates to 0b_1111_0000_1111_0000_1111_0000_1111_0000

int c = 5;      // Binary (32-bit): 0000...0000 0101
int d = ~c;     // Binary (32-bit): 1111...1111 1010 (Decimal: -6)

enum State : byte { None = 0, Active = 1, Idle = 2 }
State s = State.Active;
State inverted = ~s; 
// Evaluates to the State enum type, bypassing the standard promotion to int
2. Finalizer Declaration When prefixed to a class name within a type definition, ~ declares a finalizer (historically referred to as a destructor). A finalizer is a specialized method invoked non-deterministically by the .NET Garbage Collector (GC) when processing the finalization queue before reclaiming the object’s memory. Technical Mechanics:
  • Finalizers can only be defined within class or record class types. They are invalid in struct or record struct types.
  • The declaration cannot include access modifiers (e.g., public, private).
  • The declaration cannot accept parameters.
  • The finalizer cannot be invoked explicitly by application code.
  • During compilation, the C# compiler translates the ~ClassName() syntax into an override of the System.Object.Finalize() method, automatically wrapping the body in a try/finally block that ensures base.Finalize() is called.
public class ResourceHandler
{
    // Finalizer declaration
    ~ResourceHandler()
    {
        // Cleanup logic executed exclusively by the GC finalizer thread
    }
}
Master C# with Deep Grasping Methodology!Learn More