⬅ Previous TopicC++ Cheat Sheet
Next Topic ⮕Go Cheat Sheet
Use int
, string
, bool
, etc. to declare variables. Use var
for type inference.
int x = 10;
string name = "C#";
bool isActive = true;
var score = 99.5;
Use int
, string
, bool
, etc. to declare variables. Use var
for type inference.
int x = 10;
string name = "C#";
bool isActive = true;
var score = 99.5;
const
defines compile-time constants. readonly
for runtime constants.
const double Pi = 3.1415;
readonly string appName = "MyApp";
int i = 123;
double d = i; // implicit
int j = (int)d; // explicit
string s = i.ToString();
int parsed = int.Parse("123");
int a = 5 + 3;
bool b = (a > 3) && (a < 10);
bool equal = (a == 8);
int inc = ++a;
string name = "World";
string message = $"Hello, {name}!";
string upper = name.ToUpper();
Use ?
to declare nullable value types.
int? age = null;
if (age.HasValue) {
Console.WriteLine(age.Value);
}
int number = 10;
if (number > 0) {
Console.WriteLine("Positive");
} else {
Console.WriteLine("Non-positive");
}
switch (number) {
case 1:
Console.WriteLine("One");
break;
default:
Console.WriteLine("Other");
break;
}
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
int j = 0;
while (j < 5) {
Console.WriteLine(j);
j++;
}
do {
Console.WriteLine(j);
j++;
} while (j < 10);
foreach (var item in new int[] { 1, 2, 3 }) {
Console.WriteLine(item);
}
for (int i = 0; i < 10; i++) {
if (i == 3) continue;
if (i == 5) break;
Console.WriteLine(i);
}
goto skip;
Console.WriteLine("This won't print");
skip:
Console.WriteLine("Skipped to here");
void Greet(string name) {
Console.WriteLine($"Hello, {name}");
}
void Greet() {
Console.WriteLine("Hello, Guest");
}
void Display(string message = "Default", int count = 1) {
for (int i = 0; i < count; i++) {
Console.WriteLine(message);
}
}
Display(count: 3, message: "Hi");
void Update(ref int x) {
x += 10;
}
void Initialize(out int x) {
x = 100;
}
void Print(in int x) {
Console.WriteLine(x);
}
Func add = (a, b) => a + b;
Console.WriteLine(add(2, 3));
void Outer() {
void Inner() {
Console.WriteLine("Hello from inner");
}
Inner();
}
class Person {
public string Name;
public void Greet() {
Console.WriteLine($"Hi, I'm {Name}");
}
}
Person p = new Person();
p.Name = "Alice";
p.Greet();
class Car {
public Car() {
Console.WriteLine("Car created");
}
~Car() {
Console.WriteLine("Car destroyed");
}
}
class Animal {
public void Speak() => Console.WriteLine("Generic sound");
}
class Dog : Animal {
public void Bark() => Console.WriteLine("Woof");
}
class Base {
public virtual void Show() => Console.WriteLine("Base");
}
class Derived : Base {
public override void Show() => Console.WriteLine("Derived");
}
abstract class Shape {
public abstract void Draw();
}
class Circle : Shape {
public override void Draw() => Console.WriteLine("Draw Circle");
}
class BankAccount {
private decimal balance;
public void Deposit(decimal amount) {
if (amount > 0) balance += amount;
}
}
interface ILogger {
void Log(string message);
}
class ConsoleLogger : ILogger {
public void Log(string message) => Console.WriteLine(message);
}
class Utility {
public static int Add(int a, int b) => a + b;
}
class Book {
public string Title { get; set; }
}
class Library {
private string[] books = new string[10];
public string this[int index] {
get => books[index];
set => books[index] = value;
}
}
public
, private
, protected
, internal
, and protected internal
define access levels.
public class MyClass {
private int secret;
protected void Reveal() {}
}
delegate int Operation(int x, int y);
Operation add = (a, b) => a + b;
Console.WriteLine(add(3, 4));
class Button {
public event Action Click;
public void Press() => Click?.Invoke();
}
class Box {
public T Value;
}
var intBox = new Box { Value = 10 };
static class Extensions {
public static int Square(this int x) => x * x;
}
int value = 5;
Console.WriteLine(value.Square());
var person = new { Name = "John", Age = 30 };
Console.WriteLine(person.Name);
var tuple = (Name: "Jane", Age: 28);
Console.WriteLine(tuple.Name);
#nullable enable
string? optional = null;
if (optional != null) {
Console.WriteLine(optional.Length);
}
object obj = 42;
if (obj is int n && n > 40) {
Console.WriteLine($"Matched: {n}");
}
var numbers = new[] { 1, 2, 3, 4 };
var evens = numbers.Where(n => n % 2 == 0);
var squares = numbers.Select(n => n * n);
foreach (var s in squares) Console.WriteLine(s);
try {
int x = 0;
int y = 10 / x;
} catch (DivideByZeroException ex) {
Console.WriteLine("Cannot divide by zero");
} finally {
Console.WriteLine("Done");
}
throw new InvalidOperationException("Invalid action");
class MyException : Exception {
public MyException(string msg) : base(msg) {}
}
int[] array = { 1, 2, 3 };
List list = new List();
Dictionary dict = new();
HashSet set = new();
Queue queue = new();
Stack stack = new();
Span span = stackalloc int[3] { 1, 2, 3 };
Console.WriteLine(span[0]);
string path = "example.txt";
File.WriteAllText(path, "Hello World");
string content = File.ReadAllText(path);
using StreamWriter writer = new(path);
writer.WriteLine("Line 1");
using StreamReader reader = new(path);
string line = reader.ReadLine();
string fullPath = Path.Combine("folder", "file.txt");
if (!Directory.Exists("folder")) Directory.CreateDirectory("folder");
async Task GetDataAsync() {
await Task.Delay(1000);
return "data";
}
Task t = Task.Run(() => Console.WriteLine("Running"));
Task t2 = Task.FromResult(42);
Parallel.For(0, 10, i => Console.WriteLine(i));
var cts = new CancellationTokenSource();
Task.Run(() => {
while (!cts.Token.IsCancellationRequested) {
Console.Write(".");
Thread.Sleep(100);
}
}, cts.Token);
cts.CancelAfter(500);
var count = 5; // inferred as int
dynamic obj = "Hello";
obj = 42;
var person = new Person { Name = "Alice", Age = 30 };
using (var res = new StreamReader("file.txt")) {
Console.WriteLine(res.ReadLine());
}
string category = age switch {
< 13 => "Child",
< 20 => "Teen",
_ => "Adult"
};
public record User(string Name, int Age);
List numbers = new();
int? number = null;
namespace MyApp {
class Program {}
}
Assemblies are compiled .NET code in DLL or EXE format.
[Obsolete("Use NewMethod instead")]
void OldMethod() { }
Type type = typeof(string);
MethodInfo[] methods = type.GetMethods();
Use constructor injection and services registration with IServiceCollection
in ASP.NET Core.
Use xUnit, NUnit, or MSTest. Decorate test methods with [Fact]
or [TestMethod]
.
System
– Core typesSystem.Collections.Generic
– Lists, DictionariesSystem.IO
– File and stream handlingSystem.Threading.Tasks
– async/await and tasks
Comments