c#

Synopsis

C Sharp is a general-purpose, multi-paradigm programming language encompassing strong typing, imperative, declarative, functional, generic, object-oriented (class-based), and component-oriented programming disciplines. It was developed around 2000 by Microsoft within its .NET initiative and later approved as a standard by Ecma (ECMA-334) and ISO (ISO/IEC 23270:2018). C# is one of the programming languages designed for the Common Language Infrastructure.

Data Types

Data TypeDescriptionSize
boolBoolean data type1 bit
byteUnsigned integer1 byte
charCharacter2 bytes
decimalDecimal data type16 bytes
doubleDouble-precision floating point8 bytes
floatSingle-precision floating point4 bytes
intInteger4 bytes
longLong integer8 bytes
sbyteSigned integer1 byte
shortShort integer2 bytes
uintUnsigned integer4 bytes
ulongUnsigned long integer8 bytes
ushortUnsigned short integer2 bytes

Collections

Collections provide a more flexible way to work with groups of objects. Unlike arrays, the group of objects you work with can grow and shrink dynamically as the needs of the application change. For some collections, you can assign a key to any object that you put into the collection so that you can quickly retrieve the object by using the key.

var exampleStringList = new List<string>();   // To create and initialize a list of strings
var exampleDictionary = new Dictionary<string,string>();   // To create and initialize a dictionary which holds the key as a string and value as a string
var exampleHashset = new HashSet<int>(); // To create and initialize a HashSet of integers
var exampleArraylist = new ArrayList(); // To create and initialize an ArrayList object
var exampleHashtable = new Hashtable(); // To create and initialize a hashtable
var exampleSortedList = new SortedList<int,string>(); // To create and initialize a SortedList

Variables

Variables are containers for storing data values.

int myNum = 5;               // Integer (whole number)

double myFloatNum = 5.99D;   // Floating point number

char myLetter = 'D';         // Character

string myText = "Hello";     // String

bool myBool = true;          // Boolean

Operators

OperatorDescriptionExample
+Additionx + y
-Subtractionx - y
*Multiplicationx * y
/Divisionx / y
%Modulusx % y
++Increment++x
Decrement—x

Access Modifiers

C# has 4 basic types of access modifiers:

C# also has 2 more advanced types of access modifiers, here are all of their access levels:

Caller’s locationpublicprotected internalprotectedinternalprivate protectedprivate
Within the class
Derived class (same assembly)
Non-derived class (same assembly)
Derived class (different assembly)
Non-derived class (different assembly)

Loops

For Loop

for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

While Loop

while (condition) {
  // code block to be executed
}

Do While Loop

do {
  // code block to be executed
}
while (condition);

For Each Loop

foreach (type variableName in arrayName) {
  // code block to be executed
}

Break

When you use break, the loop will stop executing, and the program will continue to execute the code after the loop.

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    break;
  }
  Console.WriteLine(i); // 0 1 2 3
}

Continue

When you use continue, the loop will stop the current iteration, and continue with the next.

for (int i = 0; i < 10; i++) {
  if (i == 4) {
    continue;
  }
  Console.WriteLine(i); // 0 1 2 3 5 6 7 8 9
}

Switch

switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

Classes

Creating a Class

class Car {
  public void Manufacturer(string manf) {
    Console.WriteLine(manf);
  }
}

Accessing a method from a class

You should create an object from the class to access its methods.

Car tesla = new Car();
tesla.Manufacturer("Tesla Giga Factory"); 
//console prints out "Tesla Giga Factory"

Accessing a static method from a class

Static methods can be accessed without creating an object.

class Car {
  public static void Manufacturer(string manf) {
    Console.WriteLine(manf);
  }
}

Car.Manufacturer("Tesla Giga Factory");
//console prints out "Tesla Giga Factory"

Properties

Creating a Property

class Car {
  public string Model { get; set; }
}

Accessing a Property

Car tesla = new Car();
tesla.Model = "Model S"; // sets the value of the property
Console.WriteLine(tesla.Model); //prints out "Model S"

Creating and accessing a Static Property

Static properties can be accessed without creating an object.

class Car {
  public static string Model { get; set; }
}

Car.Model = "Model S";
Console.WriteLine(Car.Model); //prints out "Model S"

Enums

Enums are a data type that allows you to define a set of named constants.

Creating an Enum

The compiler automatically assigns different values to the enum members, starting with 0. You can change the default value by explicitly assigning a value to one of the enum members.

The enum can be of any numeric data type such as byte, int, long, but cannot be a string type.

enum Suits : int
{
    Club,         // 0
    Diamond,      // 1
    Heart = 3,    // 3
    Spade = 5     // 5
}

Accessing an Enum

Console.WriteLine(Suits.Club);    //Club
Console.WriteLine(Suits.Diamond); //Diamond
int heart = (int)Suits.Heart;     //3
int spade = (int)Suits.Spade;     //5

Inheritance

Creating a Base Class

class Vehicle {
  public string brand = "Ford";
  public void honk() {
    Console.WriteLine("Tuut, tuut!");
  }
}

Creating a Derived Class

This derived class inherits variables, properties, and methods from it’s parent/base class.

class Car : Vehicle {
  public string modelName = "Mustang";
}

Accessing the Base Class

Car myCar = new Car();
myCar.honk(); // Tuut, tuut!
Console.WriteLine(myCar.brand + " " + myCar.modelName); // Ford Mustang

Exception Handling

To catch exceptions, we use a try-catch block

try 
{
    string test = "Hello"
    Console.WriteLine(Convert.ToInt32(test) + 5);
}
catch (Exception ex)
{
    Console.WriteLine(ex.Message);
    //Throws an error since you can't convert "Hello" to a number
}

Here’s a list of a few common System exceptions:

Exception ClassCause of Exception
IOExceptionHandles I/O errors
SystemExceptionA failed run time check; used as a base class for other exceptions
AccessExceptionFailure to access a type member, such as a method or field
ArgumentExceptionAn argument to a method was invalid
ArgumentNullExceptionA null argument was passed to a method that does not accept it
ArgumentOutOfRangeExceptionArgument value is out of range
ArithmeticExceptionArithmetic over or underflow has occurred
FormatExceptionThe format of an argument is wrong
IndexOutofRangeExceptionAn Array index is out of range
InvalidCastExceptionAn attempt was made to cast to an invalid class
InvalidOperationExceptionA method was called at an invalid time
NotFiniteExceptionA number is not valid
NotSupportedExceptionIndicates that a method is not implemented by a class
NullReferenceExceptionAttempt to use an unassigned reference
StackOverFlowExceptionA Stack has overflowed

Custom Exceptions

You can create your own custom exceptions by inheriting from the Exception class.

throw new CustomException("This is a custom exception");