Codeloft
0 0 XP

C# reference

Short entries with an example for each. When you need every detail, each entry links to the official documentation.

C#

Console.WriteLine()

Prints a line of text to the console.

Console.WriteLine("Ready");

Variables and types

Typed variables: int, double, bool, string and more.

int age = 12;
double price = 4.99;
bool ready = true;
string name = "Ada";

String interpolation

Puts values inside text with $ and braces.

Console.WriteLine($"Total: {total}");

if / else

Runs code only when a condition is true.

if (age >= 18)
{
    Console.WriteLine("You can vote.");
}
else
{
    Console.WriteLine("Not yet.");
}

for and while

Repeat code a set number of times, or while a condition is true.

for (int i = 1; i <= 3; i++)
{
    Console.WriteLine(i);
}

Methods

Named, reusable code inside a class.

static int Square(int n)
{
    return n * n;
}

List<T> and foreach

A list that can grow; foreach visits every item.

List<string> names = new List<string>();
names.Add("Asha");
foreach (string n in names)
{
    Console.WriteLine(n);
}

Classes and objects

A class is a blueprint; new creates an object from it.

class Dog
{
    public string Name;
}

Dog rex = new Dog();
rex.Name = "Rex";

Console.ReadLine()

Reads a line of text typed by the user.

string name = Console.ReadLine();