C# Cheatsheet ZTM
C# Cheatsheet ZTM
CHEAT SHEET
CLAUDIO BERNASCONI
V1.01
HEEELLLOOOOO!
I’m Andrei Neagoie, Founder and Lead Instructor of the Zero To Mastery Academy.
After working as a Senior Software Developer over the years, I now dedicate 100% of my time to
teaching others in-demand skills, help them break into the tech industry, and advance their
careers.
In only a few years, over 1,000,000 students around the world have taken Zero To Mastery courses
and many of them are now working at top tier companies like Apple, Google, Amazon, Tesla, IBM,
Facebook, and Shopify, just to name a few.
This cheat sheet, created by our C#/.NET instructor (Claudio Bernasconi) provides you with the
key C# syntax and concepts you need to know.
If you want to not only learn C# but also get the exact steps to build your own projects and get
hired as a Developer, then check out our Career Paths.
Happy Learning!
Andrei
Starting with .NET 5, top-level statements make it possible to simplify the content of the
Program.cs file by only having the code within the static void Main method definition:
Console.WriteLine("Hello, World");
2. Data Types
Every variable and constant in C# has a type, determining the values it can hold and
operations that can be performed on it.
Value Types: Directly store the data. Once you assign a value, it holds that data.
Reference Types: Store a memory address. They point to the address of the value.
3. Variables
Variables are symbolic names for values. They play a central role in programming.
C# Cheat Sheet 1
int num = 5; // Declares an integer variable and assigns it the value 5.
string word = "Hello"; // Declares a string variable and assigns it the value "Hello".
Hint: Local variables usually start with a lowercase letter (camelCase) following the C#
naming convention guidelines.
If the C# compiler can infer (evaluate) the type of a variable, for example, when it is a
string literal, we can use var instead of explicitly using the variable type.
// We can use var because the compiler knows that "..." is a string
var name = "Peter";
// We can use var because we state that we create a new object of type Person.
var person = new Person();
The var keyword helps us keep the code short and improves readability.
4. Constants
Constants are immutable. Once their value is set, it can't be changed, ensuring some
data remains consistent throughout its use.
Hint: Constants usually start with an uppercase letter (PascalCase) following the C#
naming convention guidelines.
5. Conditional Statements
Allows you to branch your code based on conditions, making your programs dynamic.
C# Cheat Sheet 2
// ... other cases ...
default:
// Executes if no other case matches.
break;
}
Hint: If you don’t use break or return at the end of a switch case, the next case will also
be executed.
6. Loops
Useful for performing repetitive tasks.
for (int i = 0; i < 10; i++) { /*...*/ } // Loops 10 times, incrementing 'i' each time.
foreach (var item in collection) { /*...*/ } // Loops over each item in 'collection'.
while (condition) { /*...*/ } // Continues looping as long as 'condition' remains true.
do { /*...*/ } while (condition); // Executes once before checking 'condition'.
7. Arrays
Fixed-size collections that hold elements of the same type.
8. Lists
Like arrays, but can dynamically change in size.
9. Dictionaries
Associative containers that store key-value pairs.
C# Cheat Sheet 3
using System.Collections.Generic;
Dictionary<string, int> dict = new Dictionary<string, int>()
{
{"one", 1}, // "one" is the key, 1 is its associated value.
{"two", 2}
};
10. Methods
Methods encapsulate logic for reuse and clarity.
Hint: Auto-properties (as used in the example above), tell the compiler to create a
backing field. We do not have to create the backing field and fill it within the Set method
or get the value within the Get method. However, we can still implement custom logic
when required.
C# Cheat Sheet 4
12. Exception Handling
A mechanism to handle runtime errors gracefully, ensuring the program continues or
fails gracefully.
try
{
// Code that might throw an exception.
}
catch (SpecificException ex) // Catches specific exceptions, allowing tailored responses.
{
// Handle this specific error.
}
finally
{
// Cleanup code. Executes regardless of whether an exception was thrown.
}
Hint: It’s best practice to catch an exception with a specific type (e.g. SqlException) and
have a single general fallback try-catch to catch exceptions of type Exception.
Func<int, int, int> add = (a, b) => a + b; // Lambda expression. A concise way to define m
ethods.
C# Cheat Sheet 5
ata.
15. Attributes
Add metadata to your code. This metadata can be inspected at runtime.
16. Async/Await
Modern mechanism for writing non-blocking (asynchronous) code, especially useful for
I/O-bound operations.
17. Miscellaneous
enum : Defines a set of named constants.
record: A class or struct that provides special syntax and behavior for working with
data models.
struct : Lightweight class-like structures, useful for small data structures. Stored on
the stack.
var : Compiler figures out the type for you, based on the assigned value.
C# Cheat Sheet 6
nameof : Returns the name of code elements like variables, types, or members.
21. Generics
Generics allow for type-safe data structures without compromising type integrity or
performance.
C# Cheat Sheet 7
public class MyGenericClass<T> // 'T' is a placeholder for any type.
{
private T item;
public void UpdateItem(T newItem)
{
item = newItem;
}
}
22. Nullables
C# allows value types to be set to null using nullable types.
C# Cheat Sheet 8
}
}
Hint: Extension Methods are only accessible if you import (using keyword) their
namespace. Extension Methods should primarily be used when you cannot alter the
type you extend. For example, when extending a framework or third-party library type.
//Register services to the internal dependency injection container in the Program.cs file.
builder.Services.AddScoped<IService, MyService>();
C# Cheat Sheet 9
public partial class MyClass
{
public void MethodOne() { /*...*/ }
}
Hint: Many .NET frameworks, such as Blazor or ASP.NET Core make use of the partial
keyword.
27. Interoperability
C# allows interoperability with other languages, particularly with legacy Win32 API
functions.
[DllImport("user32.dll")]
public static extern int MessageBox(IntPtr h, string m, string c, int type);
var anon = new { Name = "John", Age = 25 }; // The type of 'anon' is inferred at compile t
ime.
29. Tuples
Tuples are data structures that have a specific number and sequence of elements.
C# Cheat Sheet 10
30. Pattern Matching
Introduced in later versions of C#, pattern matching simplifies certain programming
tasks.
32. Records
Records provide a concise syntax for reference types with value semantics for equality.
They're immutable and are great for data structures.
Hint: We use PascalCase for the arguments because they define (public) properties
and not fields.
C# Cheat Sheet 11
var john = new Person("John", 30);
var jane = john with { Name = "Jane" }; // jane is now ("Jane", 30)
#nullable enable
string? mightBeNull; // Reference type that might be null.
Hint: You can enable nullable reference types for specific parts of your .NET application
using the #nullable pragma, as shown in the example. Or you can enable it for the
whole .NET project within the .csproj file like this: <Nullable>enable</Nullable> .
C# Cheat Sheet 12
// Cleanup
}
}
dynamic d = 5;
d = "Hello"; // No compile-time type checking.
Additional Resources
The C#/.NET Bootcamp course
C# Documentation
C# Cheat Sheet 13