Microsoft's flagship .NET language โ behind Unity games, Windows desktop apps, ASP.NET web backends, and huge chunks of enterprise software. Strongly typed, object-oriented, with modern conveniences like LINQ built in. Copy-paste examples plus live Run/Submit exercises.
using System;
class Program {
static void Main() {
Console.WriteLine("Hello, world!");
}
}
Main method inside a class โ that's the entry point the runtime calls first.int age = 25;
string name = "Sam";
double price = 19.99;
var city = "NYC"; // var infers the type โ still statically typed
const double Pi = 3.14159; // constants can't change
int age = 20;
if (age >= 18) {
Console.WriteLine("Adult");
} else if (age >= 13) {
Console.WriteLine("Teen");
} else {
Console.WriteLine("Child");
}
for (int i = 0; i < 5; i++) {
Console.WriteLine(i);
}
int n = 3;
while (n > 0) {
Console.WriteLine(n);
n--;
}
C#'s List<T> is the go-to resizable collection, and LINQ lets you query it almost like SQL.
using System.Collections.Generic;
using System.Linq;
List<int> nums = new List<int> { 10, 20, 30 };
nums.Add(40);
Console.WriteLine(nums[0]); // 10
Console.WriteLine(nums.Count); // 4
// LINQ: filter + transform in one line
var evens = nums.Where(x => x % 2 == 0).ToList();
int total = nums.Sum();
class Dog {
public string Name { get; set; }
public int Age { get; set; }
public Dog(string name, int age) {
Name = name; Age = age;
}
public void Bark() {
Console.WriteLine(Name + " says woof!");
}
}
// var d = new Dog("Rex", 3); d.Bark();
Full runnable programs, compiled and run in a real C# (.NET/Mono) sandbox โ same workspace as the other cheat sheets.
using System;
class Program {
static void Main() {
int[] nums = { 4, 8, 15, 16, 23, 42 };
int sum = 0;
foreach (int n in nums) sum += n;
Console.WriteLine(sum);
}
}
using System;
using System.Linq;
class Program {
static string Reverse(string s) {
return new string(s.Reverse().ToArray());
}
static void Main() {
Console.WriteLine(Reverse("csharp"));
}
}
using System;
class Program {
static void Main() {
for (int i = 1; i <= 15; i++) {
if (i % 15 == 0) Console.WriteLine("FizzBuzz");
else if (i % 3 == 0) Console.WriteLine("Fizz");
else if (i % 5 == 0) Console.WriteLine("Buzz");
else Console.WriteLine(i);
}
}
}
using System;
using System.Collections.Generic;
class Program {
static void Main() {
string text = "the cat sat on the mat the cat ran";
var counts = new Dictionary<string, int>();
foreach (string word in text.Split(' ')) {
if (!counts.ContainsKey(word)) counts[word] = 0;
counts[word]++;
}
foreach (var kv in counts)
Console.WriteLine(kv.Key + ": " + kv.Value);
}
}