Author : MD TAREQ HASSAN | Updated : 2021/03/22
Standard Operators
- C# standard operators are same as standard C operators
- See: C# Operators (Arithmetic, Relational, Logical, Assignment, Precedence)
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
- conversion between compatible reference types or nullable types
- The ‘as’ operator is like a cast operation. However, if the conversion isn’t possible, ‘as’ returns null instead of raising an exception.
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:
- operator function must be a member function of the containing type
- operator function must be static
- arguments of the function are the operands
- return value of the function is the result of the operation
Tip
The string type itself uses overloaded operators. This is how concatenation works.
Note
+, * => may produce arithimetic overflow >> use checked block
/ => may rise DivideByZeroException