C#: Data Types Cheat Sheet

TypeRepresentsRangeDefault Value
boolBoolean valueTrue or FalseFalse
byte8-bit unsigned integer0 to 2550
char16-bit Unicode characterU +0000 to U +ffff‘\0’
decimal128-bit precise decimal values with 28-29 significant digits(-7.9 x 1028 to 7.9 x 1028) / 100 to 280.0M
double64-bit double-precision floating point type(+/-)5.0 x 10-324 to (+/-)1.7 x 103080.0D
float32-bit single-precision floating point type-3.4 x 1038 to + 3.4 x 10380.0F
int32-bit signed integer type-2,147,483,648 to 2,147,483,6470
long64-bit signed integer type-9,223,372,036,854,775,808 to 9,223,372,036,854,775,8070L
sbyte8-bit signed integer type-128 to 1270
short16-bit signed integer type-32,768 to 32,7670
uint32-bit unsigned integer type0 to 4,294,967,2950
ulong64-bit unsigned integer type0 to 18,446,744,073,709,551,6150
ushort16-bit unsigned integer type0 to 65,5350

C#: Type Conversion Cheat Sheet

ToBooleanConverts a type to a Boolean value, where possible.
ToByteConverts a type to a byte.
ToCharConverts a type to a single Unicode character, where possible.
ToDateTimeConverts a type (integer or string type) to date-time structures.
ToDecimalConverts a floating-point or integer type to a decimal type.
ToDoubleConverts a type to a double type.
ToInt16Converts a type to a 16-bit integer.
ToInt32Converts a type to a 32-bit integer.
ToInt64Converts a type to a 64-bit integer.
ToSbyteConverts a type to a signed byte type.
ToSingleConverts a type to a small floating-point number.
ToStringConverts a type to a string.
ToTypeConverts a type to a specified type.
ToUInt16Converts a type to an unsigned int type.
ToUInt32Converts a type to an unsigned long type.
ToUInt64Converts a type to an unsigned big integer.

C#: Variables Cheat Sheet

Integral typessbyte, byte, short, ushort, int, uint, long, ulong, and char
Floating point typesfloat and double
Decimal typesdecimal
Boolean typestrue or false values, as assigned
Nullable typesNullable data types

Defining

<data_type> <variable_list>;

Some valid variable

int i, j, k;
char c, ch;
float f, salary;
double d;

Initializing

variable_name = value;

Example

using System;

namespace VariableDefinition {
   class Program {
      static void Main(string[] args) {
         short a;
         int b ;
         double c;

         /* actual initialization */
         a = 10;
         b = 20;
         c = a + b;
         Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
         Console.ReadLine();
      }
   }
}

=> output

a = 10, b = 20, c = 30

C#: Constants Cheat Sheet

\\\ character
\'‘ character
\"” character
\?? character
\aAlert or bell
\bBackspace
\fForm feed
\nNewline
\rCarriage return
\tHorizontal tab
\vVertical tab
\xhh . . .Hexadecimal number of one or more digits

Example

using System;

namespace EscapeChar {
   class Program {
      static void Main(string[] args) {
         Console.WriteLine("Hello\tWorld\n\n");
         Console.ReadLine();
      }
   }
}

=> output

Hello   World

C#: Operators Cheat Sheet

# Arithmetic Operators

+Adds two operands
-Subtracts second operand from the first
*Multiplies both operands
/Divides numerator by de-numerator
%Modulus Operator and remainder of after an integer division
++Increment operator increases integer value by one
--Decrement operator decreases integer value by one

# Relational Operators

==Checks if the values of two operands are equal or not, if yes then condition becomes true.
!=Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.
>Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.
<Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true.
>=Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.
<=Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.

# Logical Operators

&&Called Logical AND operator. If both the operands are non zero then condition becomes true.
||Called Logical OR Operator. If any of the two operands is non zero then condition becomes true.
!Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false.

# Assignment Operators

=Simple assignment operator, Assigns values from right side operands to left side operand
+=Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand
-=Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand
*=Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand
/=Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand
%=Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand
<<=Left shift AND assignment operator
>>=Right shift AND assignment operator
&=Bitwise AND assignment operator
^=bitwise exclusive OR and assignment operator
|=bitwise inclusive OR and assignment operator

# Miscellaneous Operators

sizeof()Returns the size of a data type.
typeof()Returns the type of a class.
&Returns the address of an variable.
*Pointer to a variable.
? :Conditional Expression
isDetermines whether an object is of a certain type.
asCast without raising an exception if the cast fails.

C#: nested switch Statements Cheat Sheet

switch(ch1) {
   case 'A':
   Console.WriteLine("This A is part of outer switch" );
   
   switch(ch2) {
      case 'A':
         Console.WriteLine("This A is part of inner switch" );
         break;
      case 'B': /* inner B case code */
   }
   break;
   case 'B': /* outer B case code */
}

Example

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         int a = 100;
         int b = 200;
         
         switch (a) {
            case 100: 
            Console.WriteLine("This is part of outer switch ");
            
            switch (b) {
               case 200:
               Console.WriteLine("This is part of inner switch ");
               break;
            }
            break;
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
} 

=> output

This is part of outer switch
This is part of inner switch
Exact value of a is : 100
Exact value of b is : 200

C#: Switch Statement Cheat Sheet

switch(expression) {
   case constant-expression1  :
      statement(s);
      break;
   case constant-expression2  :
   case constant-expression3  :
      statement(s);
      break;
  
   /* you can have any number of case statements */
   default : /* Optional */
   statement(s);
}

Example

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         char grade = 'B';
         
         switch (grade) {
            case 'A':
               Console.WriteLine("Excellent!");
               break;
            case 'B':
            case 'C':
               Console.WriteLine("Well done");
               break;
            case 'D':
               Console.WriteLine("You passed");
               break;
            case 'F':
               Console.WriteLine("Better try again");
               break;
               default:
            Console.WriteLine("Invalid grade");
               break;
         }
         Console.WriteLine("Your grade is  {0}", grade);
         Console.ReadLine();
      }
   }
}

=> output

Well done
Your grade is B

C#: Nested if Statements Cheat Sheet

if( boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
   if(boolean_expression 2) {
      /* Executes when the boolean expression 2 is true */
   }
}

Example

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         //* local variable definition */
         int a = 100;
         int b = 200;
         
         /* check the boolean condition */
         if (a == 100) {
            
            /* if condition is true then check the following */
            if (b == 200) {
               /* if condition is true then print the following */
               Console.WriteLine("Value of a is 100 and b is 200");
            }
         }
         Console.WriteLine("Exact value of a is : {0}", a);
         Console.WriteLine("Exact value of b is : {0}", b);
         Console.ReadLine();
      }
   }
}

=> output

Value of a is 100 and b is 200
Exact value of a is : 100
Exact value of b is : 200

C#: if…else if…else Statement Cheat Sheet

if(boolean_expression 1) {
   /* Executes when the boolean expression 1 is true */
} 
else if( boolean_expression 2) {
   /* Executes when the boolean expression 2 is true */
} 
else if( boolean_expression 3) {
   /* Executes when the boolean expression 3 is true */
} else {
   /* executes when the none of the above condition is true */
}

Example

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 100;
         
         /* check the boolean condition */
         if (a == 10) {
            /* if condition is true then print the following */
            Console.WriteLine("Value of a is 10");
         } 
         else if (a == 20) {
            /* if else if condition is true */
            Console.WriteLine("Value of a is 20");
         } 
         else if (a == 30) {
            /* if else if condition is true  */
            Console.WriteLine("Value of a is 30");
         } else {
            /* if none of the conditions is true */
            Console.WriteLine("None of the values is matching");
         }
         Console.WriteLine("Exact value of a is: {0}", a);
         Console.ReadLine();
      }
   }
}

=> output

None of the values is matching
Exact value of a is: 100

C#: if…else Statement Cheat Sheet

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
} else {
   /* statement(s) will execute if the boolean expression is false */
}

Example

Live Demo

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 100;
         
         /* check the boolean condition */
         if (a < 20) {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 20");
         } else {
            /* if condition is false then print the following */
            Console.WriteLine("a is not less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

=> output

a is not less than 20;
value of a is : 100

C#: if Statement Cheat Sheet

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

Example

using System;

namespace DecisionMaking {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
        
         /* check the boolean condition using if statement */
         if (a < 20) {
            /* if condition is true then print the following */
            Console.WriteLine("a is less than 20");
         }
         Console.WriteLine("value of a is : {0}", a);
         Console.ReadLine();
      }
   }
}

=> output

a is less than 20;
value of a is : 10

C#: Nested Loops Cheat Sheet

do {
   statement(s);
   do {
      statement(s);
   }
   while( condition );
}
while( condition );

Example

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int i, j;
         
         for (i = 2; i < 100; i++) {
            for (j = 2; j <= (i / j); j++)
            if ((i % j) == 0) break; // if factor found, not prime
            if (j > (i / j)) Console.WriteLine("{0} is prime", i);
         }
         Console.ReadLine();
      }
   }
} 

=> output

2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime

C#: Do…While Loop Cheat Sheet

do {
   statement(s);
} while( condition );

Example

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;
         
         /* do loop execution */
         do {
            Console.WriteLine("value of a: {0}", a);
            a = a + 1;
         } 
         while (a < 20);
         Console.ReadLine();
      }
   }
} 

=> output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

C#: For Loop Cheat Sheet

for ( init; condition; increment ) {
   statement(s);
}

Example

using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         
         /* for loop execution */
         for (int a = 10; a < 20; a = a + 1) {
            Console.WriteLine("value of a: {0}", a);
         }
         Console.ReadLine();
      }
   }
} 

=> output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

C#: While Loop Cheat Sheet

while(condition) {
   statement(s);
}
using System;

namespace Loops {
   class Program {
      static void Main(string[] args) {
         /* local variable definition */
         int a = 10;

         /* while loop execution */
         while (a < 20) {
            Console.WriteLine("value of a: {0}", a);
            a++;
         }
         Console.ReadLine();
      }
   }
} 

=> output

value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19

C#: Methods Cheat Sheet

class Program
{
  static void MyMethod() 
  {
    // code to be executed
  }
}

# Call a Methods

using System;

namespace MyApplication
{
  class Program
  {
    static void MyMethod()
    {
      Console.WriteLine("I have a red banana");
    }

    static void Main(string[] args)
    {
      MyMethod();
    }
  }
}

=> output

I have a red banana

C#: Arrays Cheat Sheet

# Multidimensional Arrays

string [,] names;

Example

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         /* an array with 5 rows and 2 columns*/
         int[,] a = new int[5, 2] {{0,0}, {1,2}, {2,4}, {3,6}, {4,8} };
         int i, j;
         
         /* output each array element's value */
         for (i = 0; i < 5; i++) {
            
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0},{1}] = {2}", i, j, a[i,j]);
            }
         }
         Console.ReadKey();
      }
   }
}

=> output

a[0,0]: 0
a[0,1]: 0
a[1,0]: 1
a[1,1]: 2
a[2,0]: 2
a[2,1]: 4
a[3,0]: 3
a[3,1]: 6
a[4,0]: 4
a[4,1]: 8

# Jagged Arrays

int [][] scores;

Example

using System;

namespace ArrayApplication {
   class MyArray {
      static void Main(string[] args) {
         
         /* a jagged array of 5 array of integers*/
         int[][] a = new int[][]{new int[]{0,0},new int[]{1,2},
            new int[]{2,4},new int[]{ 3, 6 }, new int[]{ 4, 8 } };
         int i, j;
         
         /* output each array element's value */
         for (i = 0; i < 5; i++) {
            for (j = 0; j < 2; j++) {
               Console.WriteLine("a[{0}][{1}] = {2}", i, j, a[i][j]);
            }
         }
         Console.ReadKey();
      }
   }
}

=> output

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

# Passing Arrays as Function Arguments

using System;

namespace ArrayApplication {
   class MyArray {
      double getAverage(int[] arr, int size) {
         int i;
         double avg;
         int sum = 0;
         
         for (i = 0; i < size; ++i) {
            sum += arr[i];
         }
         avg = (double)sum / size;
         return avg;
      }
      static void Main(string[] args) {
         MyArray app = new MyArray();
         
         /* an int array with 5 elements */
         int [] balance = new int[]{1000, 2, 3, 17, 50};
         double avg;

         /* pass pointer to the array as an argument */
         avg = app.getAverage(balance, 5 ) ;

         /* output the returned value */
         Console.WriteLine( "Average value is: {0} ", avg );
         Console.ReadKey();
      }
   }
}

=> output

Average value is: 214.4

# Param Arrays

using System;

namespace ArrayApplication {
   class ParamArray {
      public int AddElements(params int[] arr) {
         int sum = 0;
         
         foreach (int i in arr) {
            sum += i;
         }
         return sum;
      }
   }
   class TestClass {
      static void Main(string[] args) {
         ParamArray app = new ParamArray();
         int sum = app.AddElements(512, 720, 250, 567, 889);
         
         Console.WriteLine("The sum is: {0}", sum);
         Console.ReadKey();
      }
   }
}

=> output

The sum is: 2938

# Array Class

Properties 

IsFixedSizeGets a value indicating whether the Array has a fixed size.
IsReadOnlyGets a value indicating whether the Array is read-only.
LengthGets a 32-bit integer that represents the total number of elements in all the dimensions of the Array.
LongLengthGets a 64-bit integer that represents the total number of elements in all the dimensions of the Array.
RankGets the rank (number of dimensions) of the Array.

Methods

ClearSets a range of elements in the Array to zero, to false, or to null, depending on the element type.
Copy(Array, Array, Int32)Copies a range of elements from an Array starting at the first element and pastes them into another Array starting at the first element. The length is specified as a 32-bit integer.
CopyTo(Array, Int32)Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index. The index is specified as a 32-bit integer.
GetLengthGets a 32-bit integer that represents the number of elements in the specified dimension of the Array.
GetLongLengthGets a 64-bit integer that represents the number of elements in the specified dimension of the Array.
GetLowerBoundGets the lower bound of the specified dimension in the Array.
GetTypeGets the Type of the current instance. (Inherited from Object.)
GetUpperBoundGets the upper bound of the specified dimension in the Array.
GetValue(Int32)Gets the value at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
IndexOf(Array, Object)Searches for the specified object and returns the index of the first occurrence within the entire one-dimensional Array.
Reverse(Array)Reverses the sequence of the elements in the entire one-dimensional Array.
SetValue(Object, Int32)Sets a value to the element at the specified position in the one-dimensional Array. The index is specified as a 32-bit integer.
Sort(Array)Sorts the elements in an entire one-dimensional Array using the IComparable implementation of each element of the Array.
ToStringReturns a string that represents the current object. (Inherited from Object.)

C#: Strings Cheat Sheet

# Properties

CharsGets the Char object at a specified position in the current String object.
LengthGets the number of characters in the current String object.

# Methods

public static int Compare(string strA, string strB)Compares two specified string objects and returns an integer that indicates their relative position in the sort order.
public static int Compare(string strA, string strB, bool ignoreCase )Compares two specified string objects and returns an integer that indicates their relative position in the sort order. However, it ignores the case if the Boolean parameter is true.
public static string Concat(string str0, string str1)Concatenates two string objects.
public static string Concat(string str0, string str1, string str2)Concatenates three string objects.
public static string Concat(string str0, string str1, string str2, string str3)Concatenates four-string objects.
public bool Contains(string value)Returns a value indicating whether the specified String object occurs within this string.
public static string Copy(string str)Creates a new String object with the same value as the specified string.
public void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count)Copies a specified number of characters from a specified position of the String object to a specified position in an array of Unicode characters.
public bool EndsWith(string value)Determines whether the end of the string object matches the specified string.
public bool Equals(string value)Determines whether the current String object and the specified String object have the same value.
public static bool Equals(string a, string b)Determines whether two specified String objects have the same value.
public static string Format(string format, Object arg0)Replaces one or more format items in a specified string with the string representation of a specified object.
public int IndexOf(char value)Returns the zero-based index of the first occurrence of the specified Unicode character in the current string.
public int IndexOf(string value)Returns the zero-based index of the first occurrence of the specified string in this instance.
public int IndexOf(char value, int startIndex)Returns the zero-based index of the first occurrence of the specified Unicode character in this string, starting the search at the specified character position.
public int IndexOf(string value, int startIndex)Returns the zero-based index of the first occurrence of the specified string in this instance, starting the search at the specified character position.
public int IndexOfAny(char[] anyOf)Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.
public int IndexOfAny(char[] anyOf, int startIndex)Returns the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters, starting the search at the specified character position.
public string Insert(int startIndex, string value)Returns a new string in which a specified string is inserted at a specified index position in the current string object.
public static bool IsNullOrEmpty(string value)Indicates whether the specified string is null or an Empty string.
public static string Join(string separator, params string[] value)Concatenates all the elements of a string array, using the specified separator between each element.
public static string Join(string separator, string[] value, int startIndex, int count)Concatenates the specified elements of a string array, using the specified separator between each element.
public int LastIndexOf(char value)Returns the zero-based index position of the last occurrence of the specified Unicode character within the current string object.
public int LastIndexOf(string value)Returns the zero-based index position of the last occurrence of a specified string within the current string object.
public string Remove(int startIndex)Removes all the characters in the current instance, beginning at a specified position and continuing through the last position, and returns the string.
public string Remove(int startIndex, int count)Removes the specified number of characters in the current string beginning at a specified position and returns the string.
public string Replace(char oldChar, char newChar)Replaces all occurrences of a specified Unicode character in the current string object with the specified Unicode character and returns the new string.
public string Replace(string oldValue, string newValue)Replaces all occurrences of a specified string in the current string object with the specified string and returns the new string.
public string[] Split(params char[] separator)Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array.
public string[] Split(char[] separator, int count)Returns a string array that contains the substrings in the current string object, delimited by elements of a specified Unicode character array. The int parameter specifies the maximum number of substrings to return.
public bool StartsWith(string value)Determines whether the beginning of this string instance matches the specified string.
public char[] ToCharArray()Returns a Unicode character array with all the characters in the current string object.
public char[] ToCharArray(int startIndex, int length)Returns a Unicode character array with all the characters in the current string object, starting from the specified index and up to the specified length.
public string ToLower()Returns a copy of this string converted to lowercase.
public string ToUpper()Returns a copy of this string converted to uppercase.
public string Trim()Removes all leading and trailing white-space characters from the current String object.

Example

using System;

namespace MyApplication
{
  class Program
  {
    static void Main(string[] args)
    {
      string firstName = "Hanah";
      string lastName = "Kim";
      string name = firstName + lastName;
      Console.WriteLine(name);
    }
  }
}

=> output

Hanah Kim

C#: Enums Cheat Sheet

enum <enum_name> {
   enumeration list 
};
  • The enum_name specifies the enumeration type name.
  • The enumeration list is a comma-separated list of identifiers.

Example

using System;

namespace EnumApplication {
   class EnumProgram {
      enum Colors { Red, Pink, Blue, Black, White, Purple };

      static void Main(string[] args) {
         int FistColor = (int)Colors.Red;
         int LastColor = (int)Days.Purple;
         
         Console.WriteLine("Red: {0}", FistColor);
         Console.WriteLine("Purple: {0}", LastColor);
         Console.ReadKey();
      }
   }
}

=> output

Red: 0
Purple: 5

C#: Classes and Objects Cheat Sheet

# Classes

class Car 
{
  string color = "red";
}

# Object

class Car 
{
  string color = "red";

  static void Main(string[] args)
  {
    Car myObj = new Car();
    Console.WriteLine(myObj.color);
  }
}

#Multiple Objects

class Car
{
  string color = "red";
  static void Main(string[] args)
  {
    Car myObj1 = new Car();
    Car myObj2 = new Car();
    Console.WriteLine(myObj1.color);
    Console.WriteLine(myObj2.color);
  }
}

C#: Inheritance Cheat Sheet

<access_modifier> class <base_class_name>
{
    // Base class Implementation
}
 
<access_modifier> class <derived_class_name> : <base_class_name>
{
    // Derived class implementation
}

Simple example of implementing inheritance in C#

public class X
{
    public void GetDetails()
    {
        // Method implementation
    }
}
public class Y : X
{
    // your class implementation
}
class Program
{
    static void Main(string[] args)
    {
        Y y = new Y();
        y.GetDetails();           
    }
}

Example

class Dog 
{
  public string type = "Poodle";  
  public void sound()             
  {                    
    Console.WriteLine("woof, woof!");
  }
}

class Poodle : Dog  
{
  public string typeName = "Toy";  
}

class Program
{
  static void Main(string[] args)
  {
    Poodle myPoodle = new Poodle();
    myPoodle.sound();
    Console.WriteLine(myPoodle.typeName + " " + myPoodle.type);
  }
}

=> output

woof, woof!
Toy Poodle

C#: Operator Overloading Cheat Sheet

Example

using System;

namespace OperatorOvlApplication {
   class Box {
      private double length;   // Length of a box
      private double breadth;  // Breadth of a box
      private double height;   // Height of a box

      public double getVolume() {
         return length * breadth * height;
      }
      public void setLength( double len ) {
         length = len;
      }
      public void setBreadth( double bre ) {
         breadth = bre;
      }
      public void setHeight( double hei ) {
         height = hei;
      }
      
      // Overload + operator to add two Box objects.
      public static Box operator+ (Box b, Box c) {
         Box box = new Box();
         box.length = b.length + c.length;
         box.breadth = b.breadth + c.breadth;
         box.height = b.height + c.height;
         return box;
      }
   }
   class Tester {
      static void Main(string[] args) {
         Box Box1 = new Box();   // Declare Box1 of type Box
         Box Box2 = new Box();   // Declare Box2 of type Box
         Box Box3 = new Box();   // Declare Box3 of type Box
         double volume = 0.0;    // Store the volume of a box here

         // box 1 specification
         Box1.setLength(6.0);
         Box1.setBreadth(7.0);
         Box1.setHeight(5.0);

         // box 2 specification
         Box2.setLength(12.0);
         Box2.setBreadth(13.0);
         Box2.setHeight(10.0);

         // volume of box 1
         volume = Box1.getVolume();
         Console.WriteLine("Volume of Box1 : {0}", volume);

         // volume of box 2
         volume = Box2.getVolume();
         Console.WriteLine("Volume of Box2 : {0}", volume);

         // Add two object as follows:
         Box3 = Box1 + Box2;

         // volume of box 3
         volume = Box3.getVolume();
         Console.WriteLine("Volume of Box3 : {0}", volume);
         Console.ReadKey();
      }
   }
}

=> output

Volume of Box1 : 210
Volume of Box2 : 1560
Volume of Box3 : 5400

Overloadable and Non-Overloadable Operators

+, -, !, ~, ++, --These unary operators take one operand and can be overloaded.
+, -, *, /, %These binary operators take one operand and can be overloaded.
==, !=, <, >, <=, >=The comparison operators can be overloaded.
&&, ||The conditional logical operators cannot be overloaded directly.
+=, -=, *=, /=, %=The assignment operators cannot be overloaded.
=, ., ?:, ->, new, is, sizeof, typeofThese operators cannot be overloaded.

C#: Interfaces Cheat Sheet

// interface interface Animal 
{ 
  void animalSound(); // interface method (does not have a body) 
  void run(); // interface method (does not have a body) 
}

Example

interface IAnimal 
{
  void animalSound(); 
}

class Dog : IAnimal 
{
  public void animalSound() 
  {
    Console.WriteLine("The dog says: woof woof");
  }
}

class Program 
{
  static void Main(string[] args) 
  {
    Dog myDog = new Dog();
    myDog.animalSound();
  }
}

=> output:

The dog says: woof woof

C#: Namespaces Cheat Sheet

# Defining a Namespace

namespace namespace_name {
   // code declarations
}

To call the namespace-enabled version of either function or variable:

namespace_name.item_name;

# The using Keyword

Console.WriteLine ("Hello there");

Fully qualified name

System.Console.WriteLine("Hello there");

# Nested Namespaces

namespace namespace_name1 {
   
   // code declarations
   namespace namespace_name2 {
      // code declarations
   }
}

C#: Preprocessor Directives Cheat Sheet

# Preprocessor Directives in C#
#defineIt defines a sequence of characters, called symbol.
#undefIt allows you to undefine a symbol.
#ifIt allows testing a symbol or symbols to see if they evaluate to true.
#elseIt allows creating a compound conditional directive, along with #if.
#elifIt allows for creating a compound conditional directive.
#endifSpecifies the end of a conditional directive.
#lineIt lets you modify the compiler’s line number and (optionally) the file name output for errors and warnings.
#errorIt allows generating an error from a specific location in your code.
#warningIt allows generating a level one warning from a specific location in your code.
#regionIt lets you specify a block of code that you can expand or collapse when using the outlining feature of the Visual Studio Code Editor.
#endregionIt marks the end of a #region block.
# The #define Preprocessor
#define symbol
# Conditional Directives
#if symbol [operator symbol]...

Where, symbol is the name of the symbol you want to test. You can also use true and false or prepend the symbol with the negation operator.

The operator symbol is the operator used for evaluating the symbol. Operators could be either of the following:

  • == (equality)
  • != (inequality)
  • && (and)
  • || (or)

C#: Regular Expressions Cheat Sheet

The Regex Class

public bool IsMatch(string input)Indicates whether the regular expression specified in the Regex constructor finds a match in a specified input string.
public bool IsMatch(string input, int startat)Indicates whether the regular expression specified in the Regex constructor finds a match in the specified input string, beginning at the specified starting position in the string.
public static bool IsMatch(string input, string pattern)Indicates whether the specified regular expression finds a match in the specified input string.
public MatchCollection Matches(string input)Searches the specified input string for all occurrences of a regular expression.
public string Replace(string input, string replacement)In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
public string[] Split(string input)Splits an input string into an array of substrings at the positions defined by a regular expression pattern specified in the Regex constructor.

C#: Exception Handling Cheat Sheet

The syntax for using try/catch looks like:

try {
   // statements causing exception
} catch( ExceptionName e1 ) {
   // error handling code
} catch( ExceptionName e2 ) {
   // error handling code
} catch( ExceptionName eN ) {
   // error handling code
} finally {
   // statements to be executed
}

Exception Classes

System.IO.IOExceptionHandles I/O errors.
System.IndexOutOfRangeExceptionHandles errors generated when a method refers to an array index out of range.
System.ArrayTypeMismatchExceptionHandles errors generated when the type is mismatched with the array type.
System.NullReferenceExceptionHandles errors generated from referencing a null object.
System.DivideByZeroExceptionHandles errors generated from dividing a dividend with zero.
System.InvalidCastExceptionHandles errors generated during typecasting.
System.OutOfMemoryExceptionHandles errors generated from insufficient free memory.
System.StackOverflowExceptionHandles errors generated from stack overflow.