Whether you're new to C# or a seasoned developer who needs a quick refresher, this cheat sheet is for you. Itβs a compact but powerful reference filled with practical examples and syntax reminders thatβll keep you sharp and efficient as you code.
π§± Basics
β
Variables
int age = 30;
double pi = 3.14;
string name = "Elmer";
bool isActive = true;
char initial = 'E';
β
Constants
const double Gravity = 9.81;
β
Nullable types
int? score = null;
π Conditionals & Loops
β
If-Else
if (age > 18)
Console.WriteLine("Adult");
else
Console.WriteLine("Minor");
β
Switch
switch (dayOfWeek)
{
case "Monday":
Console.WriteLine("Start of week");
break;
default:
Console.WriteLine("Any day");
break;
}
β
For loop
for (int i = 0; i < 5; i++)
Console.WriteLine(i);
β
Foreach
string[] fruits = { "Apple", "Banana" };
foreach (string fruit in fruits)
Console.WriteLine(fruit);
β
While
int counter = 0;
while (counter < 3)
{
Console.WriteLine(counter);
counter++;
}
π¦ Classes & Objects
β
Defining a Class
public class Dog
{
public string Name { get; set; }
public void Bark() => Console.WriteLine("Woof!");
}
β
Using a Class
var myDog = new Dog { Name = "Rex" };
myDog.Bark();
π― Methods
β
Method with Parameters and Return
int Add(int a, int b) => a + b;
β
Optional Parameters
void Print(string msg = "Hello") => Console.WriteLine(msg);
π§° Collections
β
Arrays
int[] nums = { 1, 2, 3 };
β
List
List<string> names = new List<string> { "Alice", "Bob" };
names.Add("Charlie");
β
Dictionary
var ages = new Dictionary<string, int> { { "Tom", 30 } };
Console.WriteLine(ages["Tom"]);
π LINQ
var evens = numbers.Where(n => n % 2 == 0).ToList();
var names = users.Select(u => u.Name).ToList();
βοΈ Exception Handling
try
{
int x = 10 / 0;
}
catch (DivideByZeroException ex)
{
Console.WriteLine("Cannot divide by zero");
}
finally
{
Console.WriteLine("Cleanup code");
}
π Async / Await
async Task<string> GetDataAsync()
{
await Task.Delay(1000);
return "Data loaded";
}
π οΈ Useful Tips
Use var when the type is obvious
Use ?? for null-coalescing:
string name = input ?? "Default";
- Use string interpolation:
Console.WriteLine($"Hello, {name}!");
π Bonus: Attributes & Enums
β
Enum
enum Status { Pending, Approved, Rejected }
β
Attribute
[Obsolete("Use NewMethod instead")]
void OldMethod() {}
π§ Final Thoughts
This cheat sheet is just the tip of the iceberg when it comes to C#. Keep it handy as a quick reference, especially when you're juggling multiple projects or switching between languages. C# is expressive, powerful, and cleanβand with a reference like this, you can focus more on building and less on remembering syntax.
Top comments (0)