Author : MD TAREQ HASSAN | Updated : 2021/03/22

Standard Operators

Special Operators

// C# special operators
x?.y    // safe navigation / conditional access
x?[]    // conditional element access
x ?? y  // Null-coalescing Operator, returns x if it is not null; otherwise, returns y

/*
default(T) : returns the default initialized value of type T, 
null for reference types, zero for numeric types, and zero/null filled in members for struct types
*/
static public T MyGenericMethod<T>(){
    T temp = default(T);
    return temp;
}

&x // address of 'x'
*x // dereferencing

/*
-> operator combines pointer dereferencing and member access
-> operator can be used only in code that is marked as unsafe
*/
x->y // is equivalent to (*x).y

typeof

System.Type type = typeof(ref or alias);  // same as ref.GetType()`

sizeof

// returns the size in bytes of the type operand
int intSize = sizeof(int);  // Constant value = 4 (4 bytes)

is

// Checks if an object is compatible with a given type
if(obj is MyObject){ }

as

bitwise complement operator

/*
~ performs a bitwise complement operation on its operand, which has the effect of reversing each bit
~ used for destructor
*/
var x = 110
var y = ~x  // 001
public class Person{
    public Person(){}   // ctor
    public ~Person(){}  // destructor
}

Overflow checking for expression

checked{
    int i3 = 2147483647 + ten;
    Console.WriteLine(i3);
}
// Checked : enables overflow checking for expression
// Unchecked : disables overflow checking for integer operations. This is the default compiler behavior

Operator precedence

Same as C operator precedence

Operator Overloading

Example: overloading ‘+’ operator to add 2 complex numbers

public struct Complex 
{
   private int real;
   private int imaginary;

   public Complex(int real, int imaginary) 
   {
      this.real = real;
      this.imaginary = imaginary;
   }
   
   public static Complex operator +(Complex c1, Complex c2) 
   {
      return new Complex(c1.real + c2.real, c1.imaginary + c2.imaginary);
   }
   
   public override string ToString()
   {
      return($"{real} + {imaginary}i");
   }

   public static void Main() 
   {
      Complex num1 = new Complex(2,3);
      Complex num2 = new Complex(3,4);

      Complex sum = num1 + num2;
      Console.WriteLine("The sum of the two numbers: {0}",sum);
 
   }
}

Conventions to follow:

Tip

The string type itself uses overloaded operators. This is how concatenation works.

Note

+, * => may produce arithimetic overflow >> use checked block
/  => may rise DivideByZeroException