layout | title |
---|---|
../../layouts/CheatSheet.astro |
C# Cheatsheet |
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 Type | Description | Size |
---|---|---|
bool | Boolean data type | 1 bit |
byte | Unsigned integer | 1 byte |
char | Character | 2 bytes |
decimal | Decimal data type | 16 bytes |
double | Double-precision floating point | 8 bytes |
float | Single-precision floating point | 4 bytes |
int | Integer | 4 bytes |
long | Long integer | 8 bytes |
sbyte | Signed integer | 1 byte |
short | Short integer | 2 bytes |
uint | Unsigned integer | 4 bytes |
ulong | Unsigned long integer | 8 bytes |
ushort | Unsigned short integer | 2 bytes |
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 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
Operator | Description | Example |
---|---|---|
+ | Addition | x + y |
- | Subtraction | x - y |
* | Multiplication | x * y |
/ | Division | x / y |
% | Modulus | x % y |
++ | Increment | ++x |
-- | Decrement | --x |
C# has 4 basic types of access modifiers:
- Public
- Private
- Protected
- Internal
C# also has 2 more advanced types of access modifiers, here are all of their access levels:
Caller's location | public | protected internal | protected | internal | private protected | private |
---|---|---|---|---|---|---|
Within the class | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
Derived class (same assembly) | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ |
Non-derived class (same assembly) | ✅ | ✅ | ❌ | ✅ | ❌ | ❌ |
Derived class (different assembly) | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
Non-derived class (different assembly) | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ |
for (statement 1; statement 2; statement 3) {
// code block to be executed
}
while (condition) {
// code block to be executed
}
do {
// code block to be executed
}
while (condition);
foreach (type variableName in arrayName) {
// code block to be executed
}
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
}
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(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
class Car {
public void Manufacturer(string manf) {
Console.WriteLine(manf);
}
}
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"
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"
class Car {
public string Model { get; set; }
}
Car tesla = new Car();
tesla.Model = "Model S"; // sets the value of the property
Console.WriteLine(tesla.Model); //prints out "Model S"
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 are a data type that allows you to define a set of named constants.
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
}
Console.WriteLine(Suits.Club); //Club
Console.WriteLine(Suits.Diamond); //Diamond
int heart = (int)Suits.Heart; //3
int spade = (int)Suits.Spade; //5
class Vehicle {
public string brand = "Ford";
public void honk() {
Console.WriteLine("Tuut, tuut!");
}
}
This derived class inherits variables, properties, and methods from it's parent/base class.
class Car : Vehicle {
public string modelName = "Mustang";
}
Car myCar = new Car();
myCar.honk(); // Tuut, tuut!
Console.WriteLine(myCar.brand + " " + myCar.modelName); // Ford Mustang
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 Class | Cause of Exception |
---|---|
IOException | Handles I/O errors |
SystemException | A failed run time check; used as a base class for other exceptions |
AccessException | Failure to access a type member, such as a method or field |
ArgumentException | An argument to a method was invalid |
ArgumentNullException | A null argument was passed to a method that does not accept it |
ArgumentOutOfRangeException | Argument value is out of range |
ArithmeticException | Arithmetic over or underflow has occurred |
FormatException | The format of an argument is wrong |
IndexOutofRangeException | An Array index is out of range |
InvalidCastException | An attempt was made to cast to an invalid class |
InvalidOperationException | A method was called at an invalid time |
NotFiniteException | A number is not valid |
NotSupportedException | Indicates that a method is not implemented by a class |
NullReferenceException | Attempt to use an unassigned reference |
StackOverFlowException | A Stack has overflowed |
You can create your own custom exceptions by inheriting from the Exception class.
throw new CustomException("This is a custom exception");