C#: reference
The language of the .NET platform: apps, Unity games, the web and services.
Program structure
Minimal program
Since C# 9 you can write code without a class or Main: these are top-level statements. Types declared in the file go after them.
Console.WriteLine("Hello, world!");
Console.WriteLine("Age: " + 16);Classic form with Main
Execution starts at the Main method. The directive using System; imports the namespace where Console lives.
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, world!");
}
}dotnet commands
Run the commands in a terminal. The project is described by the .csproj file, and the code lives in Program.cs.
dotnet new console -o Hello # create a project cd Hello dotnet run # build and run dotnet build # build only
Variables and types
Declaration
var infers the type from the initial value. const is a constant, and string? allows the value to be null.
int age = 16;
var name = "Alex";
const double Pi = 3.14;
string? city = null;
age += 1;
Console.WriteLine($"{name}, {age}, {Pi}");Basic types
decimal is meant for money, double for ordinary fractions. The suffixes m and f set the literal type, and _ separates digits.
int i = 42; long big = 10_000_000_000; double d = 3.14; decimal price = 9.99m; float f = 1.5f; bool ok = true; char c = 'A'; string s = "text";
Type conversion
Parse throws an exception on bad text, TryParse returns false. The explicit cast (int) drops the fractional part.
int n = int.Parse("12");
bool ok = int.TryParse("abc", out int m);
int y = (int)3.9;
string s = 42.ToString();
long z = Convert.ToInt64("5");
Console.WriteLine($"{n} {ok} {m} {y} {s} {z}");Strings
Interpolation and literals
$"...{x}" inserts values, a format goes after :. @"..." does not process \, and """...""" is a multi-line raw string.
string name = "Alex";
int age = 16;
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine($"{3.14159:F2} {age,5} {age:D4}");
string path = @"C:\temp\file.txt";
string multi = """
First line
Second line
""";String methods
Strings are immutable: Trim, Replace, ToUpper return a new string. Split cuts the text, and string.Join glues the parts together.
string s = " Hello, C# ";
string t = s.Trim();
Console.WriteLine(t.ToUpper());
Console.WriteLine(t.Replace("C#", "world"));
Console.WriteLine(string.Join("|", t.Split(',')));
Console.WriteLine(t.Contains("C#"));
Console.WriteLine(t.Substring(0, 5));
Console.WriteLine(t.Length);StringBuilder
StringBuilder is handy when a string is built piece by piece in a loop: it does not create a new string on every change.
using System.Text;
var sb = new StringBuilder();
sb.Append("a").Append(1).AppendLine("!");
sb.Insert(0, ">");
Console.WriteLine(sb.ToString());Conditions
if and the ternary operator
The condition in parentheses must be a bool. The form cond ? a : b picks one of two values.
int n = 7;
if (n % 2 == 0) Console.WriteLine("even");
else if (n > 5) Console.WriteLine("odd and greater 5");
else Console.WriteLine("odd");
string kind = n < 0 ? "minus" : "plus";switch
Every case branch ends with break. Several labels in a row share one branch, and default catches the remaining values.
int day = 6;
switch (day)
{
case 6:
case 7:
Console.WriteLine("weekend");
break;
default:
Console.WriteLine("weekday");
break;
}switch expression
switch as an expression returns a value. The patterns and, or and comparisons make it more compact, and _ means "everything else".
int day = 6;
string type = day switch
{
>= 1 and <= 5 => "weekday",
6 or 7 => "weekend",
_ => "unknown"
};
Console.WriteLine(type);is patterns
is checks the type and can declare a variable right away (int x). Negation is written as is not.
object o = 42;
if (o is int x && x > 10)
Console.WriteLine($"big {x}");
if (o is not string)
Console.WriteLine("not a string");Loops
for, while, do
do ... while checks the condition after the body, so the body runs at least once.
for (int i = 0; i < 3; i++)
Console.WriteLine(i);
int n = 3;
while (n > 0) n--;
do { n++; } while (n < 3);foreach
foreach walks over any collection and over a string. You cannot change the loop variable inside the body.
int[] nums = { 10, 20, 30 };
foreach (int v in nums)
Console.WriteLine(v);
foreach (char ch in "C#")
Console.WriteLine(ch);break and continue
continue jumps to the next iteration, break leaves the loop completely.
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0) continue;
if (i > 7) break;
Console.WriteLine(i);
}Methods
Declaration
The return type is written before the name, void means "returns nothing". The => form is a shortcut for a single-expression method.
static int Add(int a, int b) => a + b;
static void Greet(string name)
{
Console.WriteLine($"Hello, {name}!");
}
Console.WriteLine(Add(2, 3));
Greet("Alex");Parameters
A parameter can have a default value and be called by name. out returns an extra value through a parameter.
static double Area(double w, double h = 1) => w * h;
static bool TryDiv(int a, int b, out int result)
{
result = b == 0 ? 0 : a / b;
return b != 0;
}
Console.WriteLine(Area(h: 2, w: 3));
Console.WriteLine(Area(5));
if (TryDiv(10, 2, out int q)) Console.WriteLine(q);Lambdas and delegates
Func returns a value, Action does not, Predicate returns a bool. A lambda x => ... is a short form of an anonymous method.
Func<int, int> square = x => x * x;
Action<string> say = s => Console.WriteLine(s);
Predicate<int> even = n => n % 2 == 0;
say("ok");
Console.WriteLine(square(5));
Console.WriteLine(even(4));Tuples
A tuple (A, B) lets you return several values, and var (x, y) = ... unpacks them into variables.
static (int Min, int Max) Order(int a, int b) =>
(Math.Min(a, b), Math.Max(a, b));
var (lo, hi) = Order(5, 2);
Console.WriteLine($"{lo} {hi}");Collections
Array and List
An array has a fixed length (Length), while List<T> grows (Count). The form [...] is a collection expression from C# 12.
int[] arr = { 1, 2, 3 };
int[] zeros = new int[5];
var list = new List<int> { 1, 2, 3 };
list.Add(4);
list.Remove(1);
List<string> names = ["Amy", "Ivan"];
Console.WriteLine($"{arr.Length} {list.Count} {names[0]}");Dictionary
Dictionary stores key-value pairs. TryGetValue reads a value safely, Add throws an exception on a repeated key.
var ages = new Dictionary<string, int>
{
["Amy"] = 16,
["Ivan"] = 17
};
ages["Amy"]++;
ages.Add("Peter", 18);
if (ages.TryGetValue("Amy", out int age)) Console.WriteLine(age);
Console.WriteLine(ages.ContainsKey("Hanna"));
foreach (var (name, a) in ages) Console.WriteLine($"{name}: {a}");HashSet, Stack, Queue
HashSet keeps no duplicates, Stack works as "last in, first out", and Queue as "first in, first out".
var set = new HashSet<int> { 1, 2, 2, 3 };
Console.WriteLine(set.Count);
var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
Console.WriteLine(stack.Pop());
var queue = new Queue<string>();
queue.Enqueue("a");
Console.WriteLine(queue.Dequeue());Indexes and ranges
^1 is an index from the end, and a..b is a range from a up to but not including b. It works for arrays and strings.
int[] a = { 1, 2, 3, 4, 5 };
Console.WriteLine(a[^1]);
int[] part = a[1..3];
Console.WriteLine(string.Join(",", part));
string s = "Hello";
Console.WriteLine(s[1..4]);Classes, records, enums
Class
A class holds fields, a constructor and methods. override ToString sets the text form of an object. In a file with top-level statements, put the class after them.
var p = new Point(3, 4);
Console.WriteLine($"{p} {p.Dist()}");
class Point
{
public int X, Y;
public Point(int x, int y) { X = x; Y = y; }
public double Dist() => Math.Sqrt(X * X + Y * Y);
public override string ToString() => $"({X}, {Y})";
}record
record is an immutable data type compared by value. The with expression makes a copy with a changed property.
var u = new User("Alex", 16);
var u2 = u with { Age = 17 };
Console.WriteLine(u);
Console.WriteLine(u == u2);
record User(string Name, int Age);enum and struct
enum is a set of named constants numbered from zero. struct is a value type: it is copied on assignment.
Color c = Color.Green;
Console.WriteLine($"{c} {(int)c}");
var pt = new Pair(1, 2);
Console.WriteLine(pt.A + pt.B);
enum Color { Red, Green, Blue }
struct Pair
{
public int A, B;
public Pair(int a, int b) { A = a; B = b; }
}Primary constructor
Since C# 12 constructor parameters can be listed right in the class header and then used in its methods.
var d = new Dog("Rex");
d.Bark();
class Dog(string name)
{
public void Bark() => Console.WriteLine($"{name}: woof!");
}Properties
Auto-properties
A property { get; set; } replaces a field with accessor methods. init allows setting a value only at creation, and => makes a computed property.
var acc = new Account { Owner = "Amy" };
acc.Balance = 100;
Console.WriteLine($"{acc.Owner} {acc.Balance} {acc.IsRich}");
class Account
{
public string Owner { get; init; } = "";
public decimal Balance { get; set; }
public bool IsRich => Balance > 50;
}Custom get and set
The implicit value is available in set. This is how validation is added to a property, and the hidden field usually starts with _.
var t = new Temp();
t.Celsius = -300;
Console.WriteLine(t.Celsius);
class Temp
{
private double _c;
public double Celsius
{
get => _c;
set => _c = value < -273.15 ? -273.15 : value;
}
}Interfaces and inheritance
Interface
An interface describes methods a class must implement. A variable of the interface type can hold an object of any such class.
IShape s = new Circle(2);
Console.WriteLine(s.Area());
interface IShape { double Area(); }
class Circle(double r) : IShape
{
public double Area() => Math.PI * r * r;
}Inheritance and virtual
A class inherits another after :. A virtual method can be changed with override, and the version of the real type is called.
Animal a = new Cat();
a.Speak();
class Animal
{
public virtual void Speak() => Console.WriteLine("...");
}
class Cat : Animal
{
public override void Speak() => Console.WriteLine("Meow");
}LINQ
Where, Select, ToList
LINQ works with any collection (using System.Linq is needed). Where filters, Select transforms, ToList gathers the result.
using System.Linq;
int[] v = { 1, 2, 3, 4, 5, 6 };
var sq = v.Where(x => x % 2 == 0).Select(x => x * x).ToList();
Console.WriteLine(string.Join(", ", sq));Sum, Max, Any
The methods Sum, Max, Average, Count compute a result, Any and All check a condition, First takes the first matching element.
int[] v = { 3, 8, 1 };
Console.WriteLine(v.Sum());
Console.WriteLine(v.Max());
Console.WriteLine(v.Average());
Console.WriteLine(v.Any(x => x > 5));
Console.WriteLine(v.First(x => x > 1));
Console.WriteLine(v.Count(x => x < 5));OrderBy and GroupBy
OrderBy sorts, ThenBy adds a second key. GroupBy groups elements by a key, available as g.Key.
string[] words = { "pear", "fig", "apple", "fig" };
var sorted = words.OrderBy(w => w.Length).ThenBy(w => w);
var groups = words.GroupBy(w => w).Select(g => $"{g.Key}:{g.Count()}");
Console.WriteLine(string.Join(" ", sorted));
Console.WriteLine(string.Join(" ", groups));from ... select query
This is another syntax for the same operations, similar to SQL. Internally it turns into calls of Where and Select.
var q = from x in new[] { 1, 2, 3, 4 }
where x > 1
select x * 10;
Console.WriteLine(string.Join(",", q));Error handling
try, catch, finally
Code that may fail goes into try. catch handles an exception of a given type, and finally always runs.
try
{
int n = int.Parse("abc");
}
catch (FormatException e)
{
Console.WriteLine($"Error: {e.Message}");
}
finally
{
Console.WriteLine("the end");
}throw
An exception is created and thrown with throw new .... For bad arguments there is ArgumentException.
static void Check(int age)
{
if (age < 0) throw new ArgumentException("Invalid age");
}
try { Check(-1); }
catch (ArgumentException e)
{
Console.WriteLine(e.Message);
}Nullable
?. skips the call on null, ?? gives a fallback value, ??= assigns if the value is null. int? is a number that can be empty.
string? name = null; Console.WriteLine(name?.Length); Console.WriteLine(name ?? "none"); name ??= "Alex"; Console.WriteLine(name.Length); int? maybe = null; Console.WriteLine(maybe.HasValue); Console.WriteLine(maybe.GetValueOrDefault(5));
using and Dispose
using calls Dispose for you and releases the resource (file, stream) at the end of the block or scope.
using System.IO;
using var reader = new StringReader("a\nb");
Console.WriteLine(reader.ReadLine());
using (var w = new StringWriter())
{
w.Write("x");
Console.WriteLine(w);
}async and await
async method
A method with async returns Task<T>. The await operator waits for the result without blocking the thread. It is also allowed in Main and in top-level statements.
Console.WriteLine(await GetNumberAsync());
static async Task<int> GetNumberAsync()
{
await Task.Delay(100);
return 42;
}Task.WhenAll
Task.Run starts work in the background, and Task.WhenAll waits until all tasks finish and returns an array of results.
var t1 = Task.Run(() => 1 + 1); var t2 = Task.Run(() => 2 + 2); int[] results = await Task.WhenAll(t1, t2); Console.WriteLine(results[0] + results[1]);
Namespaces and packages
namespace
namespace groups types and avoids name clashes. The form with a semicolon applies to the whole file and appeared in C# 10.
namespace Shop.Models;
public class Product
{
public string Title { get; set; } = "";
}using and aliases
using imports a namespace, using static lets you call static methods without the class name, and Json = creates a short name.
using Shop.Models;
using static System.Math;
using Json = System.Text.Json.JsonSerializer;
var p = new Product { Title = "Book" };
Console.WriteLine(Sqrt(16));NuGet packages
External libraries are added as NuGet packages. The commands change the .csproj, and restore downloads the dependencies.
dotnet add package Newtonsoft.Json dotnet add reference ../Lib/Lib.csproj dotnet restore
What is next
A lessons course for this language is on the way, and the reference is already available.