Skip to content

Instantly share code, notes, and snippets.

@EVanGorkom
Last active March 14, 2024 17:35
Show Gist options
  • Save EVanGorkom/c799a02ed02f3808932aa36f05d7f36e to your computer and use it in GitHub Desktop.
Save EVanGorkom/c799a02ed02f3808932aa36f05d7f36e to your computer and use it in GitHub Desktop.

C# Cheatsheet

Variables

We use variables to temporarily store data in the computer’s memory. In C#, the type of a variable should be specified at the time of declaration.

Types

In C#, we have two categories of types:

  • Value Types: for storing simple values directly.
  • Reference Types: for storing references to objects.

Primitive Types

Type Bytes Range
byte 1 0 to 255
short 2 -32,768 to 32,767
int 4 -2,147,483,648 to 2,147,483,647
long 8 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 ±1.5 x 10^-45 to ±3.4 x 10^38
double 8 ±5.0 x 10^-324 to ±1.7 x 10^308
char 2 Unicode symbols
bool 1 True or False

Reference Types

Reference types in C# include classes, interfaces, arrays, delegates, and more. They store references to objects in memory.

DateTime now = DateTime.Now;

Declaring Variables

byte age = 30;
long viewsCount = 3_123_456L;
float price = 10.99F;
char letter = 'A';
bool isEligible = true;
  • In C#, we terminate statements with a semicolon.
  • Characters are enclosed with single quotes and strings with double quotes.
  • Numeric types have default values (e.g., int defaults to 0).
  • Suffixes like 'L' for long and 'F' for float can be used.

Comments:

We use comments to add notes to our code.

// This is a comment and it won’t get executed.

Strings

Strings in C# are objects of the System.String class. They are reference types.

string name = "Eric";

Useful String Methods:

The String class in C# provides a number of useful methods:

  • StartsWith("a")
  • EndsWith("a")
  • Length
  • IndexOf("a")
  • Replace("a", "b")
  • ToUpper()
  • ToLower()

Strings are immutable in C#, meaning their values cannot be changed once initialized.

String Interpolation:

string name = "Alice";
int age = 30;
Console.WriteLine($"My name is {name} and I am {age} years old.");

Escape Sequences:

Common escape sequences:

  • \\ (backslash)
  • \" (double quote)
  • \n (newline)
  • \t (tab)

Arrays

We use arrays to store a list of objects of the same type.

// Creating and initializing an array of 5 elements 
int[] numbers = new int[3];
numbers[0] = 10;
numbers[1] = 20;
numbers[2] = 30;

// Shortcut
int[] numbers = { 10, 20, 30 };

C# arrays have a fixed length. If you need dynamic resizing, consider using collections like List<T>.

Useful Array Methods:

Arrays in C# provide methods like Sort and ToString.

int[] numbers = { 4, 2, 7 };
Array.Sort(numbers);
string result = string.Join(", ", numbers);
Console.WriteLine(result);

Multi-dimensional Arrays:

// Creating a 2x3 array (two rows, three columns)
int[,] matrix = new int[2, 3];
matrix[0, 0] = 10;

// Shortcut
int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 } };

Constants

Constants (readonly variables) have a fixed value that cannot be changed after initialization.

readonly float INTEREST_RATE = 0.04f;

By convention, constants are named in PascalCase.

Arithmetic Expressions

int x = 10 + 3;
int x = 10 - 3;
int x = 10 * 3;
int x = 10 / 3; // integer division
float x = 10f / 3f; // floating-point division
int x = 10 % 3; // modulus (remainder)

Order of Operations:

Parentheses can be used to control the order of operations.

Increment and Decrement Operators

int x = 1;
x++; // Equivalent to x = x + 1
x--; // Equivalent to x = x - 1

Casting

In C#, we have two types of casting:

  • Implicit: happens automatically when converting types that are compatible.
  • Explicit: requires a cast operator.
// Implicit casting
int x = 1;
float y = x;

// Explicit casting
float x = 1.5f;
int y = (int)x;

To convert strings to numbers, use methods like int.Parse or float.Parse.

Control Flow

Comparison Operators

x == y // equality operator
x != y // inequality operator
x > y
x >= y
x < y
x <= y

Logical Operators

x && y // logical AND
x || y // logical OR
!x // logical NOT

If Statements

if (condition1)
{
    statement1;
}
else if (condition2)
{
    statement2;
}
else
{
    statement3;
}

Ternary Operator

string className = (income > 100_000) ? "First" : "Economy";

Switch Statements

switch (x)
{
    case 1:
        // code
        break;
    case 2:
        // code
        break;
    default:
        // code
        break;
}

For Loops

for (int i = 0; i < 5; i++)
{
    // code
}

While Loops

while (condition)
{
    // code
}

Do..While Loops

do
{
    // code
} while (condition);

For-each Loops

int[] numbers = { 1, 2, 3, 4 };
foreach (int number in numbers)
{
    // code
}

Commonly Used Methods

String Methods:

  • Length: Returns the length of the string.

    string str = "hello";
    int length = str.Length; // length = 5
  • ToUpper, ToLower: Converts the string to uppercase or lowercase.

    string str = "Hello";
    string upper = str.ToUpper(); // upper = "HELLO"
    string lower = str.ToLower(); // lower = "hello"
  • Substring: Retrieves a substring from the original string.

    string str = "Hello World";
    string sub = str.Substring(6); // sub = "World"

Array Methods:

  • Length: Returns the number of elements in the array.

    int[] numbers = { 1, 2, 3, 4, 5 };
    int length = numbers.Length; // length = 5
  • Sort: Sorts the elements of the array.

    int[] numbers = { 3, 1, 4, 2, 5 };
    Array.Sort(numbers); // numbers = { 1, 2, 3, 4, 5 }
  • IndexOf: Searches for the specified object and returns the index of the first occurrence within the entire array.

    int[] numbers = { 1, 2, 3, 4, 5 };
    int index = Array.IndexOf(numbers, 3); // index = 2

List Methods:

  • Add: Adds an object to the end of the List.

    List<int> numbers = new List<int>();
    numbers.Add(1);
    numbers.Add(2);
  • Remove: Removes the first occurrence of a specific object from the List.

    List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
    numbers.Remove(3); // numbers = { 1, 2, 4, 5 }
  • Contains: Determines whether an element is in the List.

    List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
    bool containsThree = numbers.Contains(3); // containsThree = true

Dictionary/Hash Methods:

  • Add: Adds the specified key and value to the dictionary.

    Dictionary<string, int> ages = new Dictionary<string, int>();
    ages.Add("Alice", 30);
    ages.Add("Bob", 25);
  • Remove: Removes the value with the specified key from the dictionary.

    Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 } };
    ages.Remove("Alice"); // removes Alice and her age from the dictionary
  • ContainsKey: Determines whether the dictionary contains the specified key.

    Dictionary<string, int> ages = new Dictionary<string, int> { { "Alice", 30 }, { "Bob", 25 } };
    bool containsAlice = ages.ContainsKey("Alice"); // containsAlice = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment