ZetCode

C# basics

last modified October 18, 2026

In this article we cover basic programming concepts of the C# language. We introduce the very basic programs. We work with variables, constants, and basic data types. We read from and write to the console; we use string interpolation.

The examples were written for .NET 10 and C# 14, but they work in older versions unless noted. To run them, we need the .NET SDK.

$ dotnet new console -o hello
$ cd hello
$ dotnet run
Hello, World!

The dotnet new console command creates a console project with a Program.cs file and a project file. We put the code of the examples into Program.cs and start it with dotnet run. Since .NET 10 we can also run a single file without a project: dotnet run Program.cs.

C# old school example

We start with a traditional C# example. This is the form used in the books and tutorials written before 2021, and still seen in much existing code.

Program.cs
using System;

namespace Simple
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("This is C#");
        }
    }
}

The program prints the "This is C#" message to the console. We explain it line by line.

using System;

The using directive imports a namespace to our program. Namespaces group named entities and prevent name conflicts. Each statement ends with a semicolon.

namespace Simple
{

We declare a namespace. Namespaces are used to organize code and to prevent name clashes.

class Program
{
    ...
}

A C# program consists of types, such as classes, and their members. A class is a basic building block of a C# program. The definition has a body, which starts with a left curly brace { and ends with a right curly brace }.

static void Main(string[] args)
{
    ...
}

Main is a method. A method is a piece of code created to do a specific job. Instead of putting all the code into one place, we divide it into pieces, called methods. This brings modularity to our application. The body of a method is enclosed in curly brackets.

The specific job of the Main method is to start the application. It is the entry point of each C# program. The method is declared static, so it can be called without creating an instance of the Program class; the program has to start before any object can be created. The void keyword signifies that the method does not return any value.

The Main method has the args parameter, which stores the command line arguments. Through them, users of the program can pass it values.

Console.WriteLine("This is C#");

To print a message to the console, we use the WriteLine method of the Console class. The class represents the standard input, output, and error streams of console applications. The Console class is part of the System namespace, which is the reason for the using System; directive. Without it, we would write the fully qualified name: System.Console.WriteLine("This is C#");.

$ dotnet run
This is C#

C# basic example simplified

Over the years, C# has been significantly simplified, and the language became much more approachable for beginners.

Program.cs
namespace Simple;

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("This is C#");
    }
}

Since C# 10 and the .NET 6 SDK, we can omit the using System; directive. It is included automatically through implicit usings, which the project file enables with <ImplicitUsings>enable</ImplicitUsings>. The implicit usings cover the most common namespaces, such as System, System.IO, System.Linq, and System.Collections.Generic.

namespace Simple;

The namespace declaration can be reduced as well (C# 10). This is called a file-scoped namespace, and it saves a level of braces and indentation.


With top-level statements (C# 9), we can simplify the code further. We do not need the Main method as a starting point, and the code does not have to be placed inside a class.

Note: Only one file in the application may use top-level statements. The compiler generates the Main method for us, and the args variable is available in the code.

For small programs, we can also omit the namespace declaration.

Program.cs
Console.WriteLine("This is C#");

Now the original 12-line example is reduced to a single line of code. In the rest of the tutorials, we use top-level statements.

C# console reading values

We use the Console class to read values as well.

Program.cs
Console.Write("Enter your name: ");

string? name = Console.ReadLine();

if (string.IsNullOrWhiteSpace(name))
{
    Console.WriteLine("No name given");
    return;
}

Console.WriteLine($"Hello {name.Trim()}");

Console.Write("Enter your age: ");

if (int.TryParse(Console.ReadLine(), out int age))
{
    Console.WriteLine($"Next year you will be {age + 1}");
}
else
{
    Console.WriteLine("That is not a number");
}

The program reads a name and an age from the console and prints a message.

string? name = Console.ReadLine();

We read a line from the terminal. When we hit the Enter key, the input is assigned to the name variable. The type is string?, because ReadLine returns null at the end of the input stream (for example, when the input is redirected from an empty file, or the user presses Ctrl+D). Ignoring this possibility gives a compiler warning about a possible null reference.

if (string.IsNullOrWhiteSpace(name))
{
    Console.WriteLine("No name given");
    return;
}

We check the input. The IsNullOrWhiteSpace method is true for null, an empty string, and a string of spaces. The return statement ends a program that uses top-level statements.

if (int.TryParse(Console.ReadLine(), out int age))

The input is text. To get a number, we convert it. int.TryParse returns false for invalid text instead of throwing an exception, which is the right choice for user input. See the string to int conversion tutorial.

$ dotnet run
Enter your name: Jan
Hello Jan
Enter your age: 34
Next year you will be 35

With an empty name or an invalid age, the program prints "No name given" or "That is not a number".

C# command line arguments

C# programs can receive command line arguments. They follow the name of the program when we run it. A C# program receives command line arguments in the args array of strings.

Program.cs
Console.WriteLine($"{args.Length} arguments");

for (int i = 0; i < args.Length; i++)
{
    Console.WriteLine($"{i}: {args[i]}");
}

// the same with foreach
foreach (string arg in args)
{
    Console.WriteLine(arg.ToUpper());
}

The program prints the number of arguments and the arguments.

for (int i = 0; i < args.Length; i++)
{
    Console.WriteLine($"{i}: {args[i]}");
}

We go through the array of arguments with a for loop and print them with their indexes. The Length property gives the number of elements of the array. The second loop shows the shorter foreach form.

$ dotnet run -- 1 2 "three words"
3 arguments
0: 1
1: 2
2: three words
1
2
THREE WORDS

We provide three arguments. The double dash separates the options of dotnet from the arguments of our program. A value with spaces is quoted, and it forms one argument. All the arguments are strings; numbers must be parsed. For more complex command lines, see the command line arguments tutorial.

C# variables

A variable is a place to store data. A variable has a name and a data type. A data type determines what values can be assigned to the variable, for instance integers, strings, or boolean values. Over the time of the program, a variable can obtain various values of the same data type. C# is statically typed, and a local variable must be assigned a value before it is read.

Program.cs
string city = "New York";
string name = "Paul";
int age = 35;
string nationality = "American";

Console.WriteLine(city);
Console.WriteLine(name);
Console.WriteLine(age);
Console.WriteLine(nationality);

city = "London";
Console.WriteLine(city);

// age = "thirty";          // error CS0029: a string cannot be assigned to an int

int count;
// Console.WriteLine(count);  // error CS0165: use of unassigned local variable
count = 3;
Console.WriteLine(count);

In the example, we have four variables and an unassigned one.

string city = "New York";

We declare a city variable of the string type and initialize it to the "New York" value.

city = "London";

We assign a new value to the city variable. The commented-out assignment of a string to the int variable would not compile.

int count;
// Console.WriteLine(count);
count = 3;

We can declare a variable without a value, but reading it before it is assigned is a compile-time error.

$ dotnet run
New York
Paul
35
American
London
3

The C# variable tutorial covers variables in detail.

The var keyword

Local variables can be implicitly typed using the var keyword. The variables are still strongly typed; the type is inferred by the C# compiler from the right side of the assignment.

Program.cs
var name = "Peter";
var age = 23;

Console.WriteLine($"{name} is {age} years old");

name = "Jozef";
age = 32;

Console.WriteLine($"{name} is {age} years old");

Console.WriteLine(name.GetType());
Console.WriteLine(age.GetType());

var price = 9.99;
var amount = 9.99m;
var big = 3_000_000_000;
var flag = true;
var letter = 'x';

Console.WriteLine($"{price.GetType().Name} {amount.GetType().Name} {big.GetType().Name} {flag.GetType().Name} {letter.GetType().Name}");

In the program, we have several implicitly typed variables.

var name = "Peter";
var age = 23;

On the left side of the assignment, we use the var keyword. The name variable is of the string type and age is an int. The type is fixed from the declaration on; assigning a string to age later would not compile.

var price = 9.99;
var amount = 9.99m;
var big = 3_000_000_000;

The suffix of a literal decides its type: a literal with a decimal point is a double, with the m suffix it is a decimal. A whole number literal is an int if it fits, otherwise a uint, long, or ulong; three billion fits into a uint. Underscores in a number are a visual separator. Use decimal for money, since double cannot represent 0.1 exactly.

$ dotnet run
Peter is 23 years old
Jozef is 32 years old
System.String
System.Int32
Double Decimal UInt32 Boolean Char

C# collections

While variables hold single values, multiple values can be added to collections. A List<T> is a sequence of elements, which can be accessed by the index operator []. Elements of a list can be traversed with the foreach keyword. The List<T> type resides in the System.Collections.Generic namespace, which is included with the implicit usings.

Program.cs
List<string> words = ["stone", "rock", "falcon", "sky"];

Console.WriteLine(words[2]);
Console.WriteLine(words[^1]);          // the last element
Console.WriteLine(words.Count);

Console.WriteLine();

foreach (var word in words)
{
    Console.WriteLine(word);
}

words.Add("cloud");
words.Remove("rock");
Console.WriteLine(string.Join(", ", words));

// an array has a fixed size
int[] numbers = [1, 2, 3, 4, 5];
Console.WriteLine(numbers.Sum());
Console.WriteLine(numbers[1..4].Length);

// a dictionary maps keys to values
var capitals = new Dictionary<string, string>
{
    ["Slovakia"] = "Bratislava",
    ["Hungary"] = "Budapest"
};

Console.WriteLine(capitals["Hungary"]);

In the example, we work with a list of words, an array, and a dictionary.

List<string> words = ["stone", "rock", "falcon", "sky"];

A list object is created with a collection expression (C# 12). Between the angle brackets, we specify the data type of the list elements. The elements are separated with commas.

Console.WriteLine(words[2]);
Console.WriteLine(words[^1]);

Here we print the third element. The indexes start from 0. The ^1 index means "from the end": the last element.

foreach (var word in words)
{
    Console.WriteLine(word);
}

Using the foreach loop, we go through all the elements of the list. In each cycle, the word variable holds one of the elements.

int[] numbers = [1, 2, 3, 4, 5];
Console.WriteLine(numbers[1..4].Length);

An array has a fixed size. The range 1..4 selects the elements from index 1 up to, but not including, index 4.

var capitals = new Dictionary<string, string>
{
    ["Slovakia"] = "Bratislava",
    ["Hungary"] = "Budapest"
};

A dictionary maps keys to values. Lookups by key are fast.

$ dotnet run
falcon
sky
4

stone
rock
falcon
sky
stone, falcon, sky, cloud
15
3
Budapest

C# discards

Discards are special, write-only variables which are used to ignore the values that are not interesting to the programmer. The _ (underscore character) is used for a discard.

Program.cs
var vals = (1, 2, 3, 4, 5, 6);

(int x, int y, int z, _, _, _) = vals;

Console.WriteLine(x);
Console.WriteLine(y);
Console.WriteLine(z);

// a discard in an out parameter
if (int.TryParse("42", out _))
{
    Console.WriteLine("it is a number");
}

// named tuple elements are clearer
var person = (Name: "John", Age: 34);
Console.WriteLine($"{person.Name} is {person.Age}");

var (name, _) = person;
Console.WriteLine(name);

The example defines a tuple of values. By using a deconstruction, we assign the values of the tuple to variables.

var vals = (1, 2, 3, 4, 5, 6);

We define a tuple of six values. A tuple is a collection of ordered, possibly heterogeneous elements.

(int x, int y, int z, _, _, _) = vals;

We are interested only in the first three values of the tuple. On the left side of the assignment, we define the variables x, y, and z. Since the tuple has six elements, we need six places on the left side as well. For the remaining ones, we use the _ discard to say that these values are not important to us.

if (int.TryParse("42", out _))

Discards are also used for out parameters whose value we do not need. Named tuple elements, as in (Name: "John", Age: 34), make tuples easier to read.

$ dotnet run
1
2
3
it is a number
John is 34
John

C# Range method

The Enumerable.Range method generates a sequence of numbers within a specified range. The first parameter is the value of the first integer in the sequence. The second parameter is the number of sequential integers to generate, not the last value.

Program.cs
foreach (var el in Enumerable.Range(1, 10))
{
    Console.Write($"{el} ");
}

Console.WriteLine();

// the for loop and a range of indexes
for (int i = 10; i > 0; i -= 3)
{
    Console.Write($"{i} ");
}

Console.WriteLine();

Console.WriteLine(string.Join(",", Enumerable.Range(1, 5).Select(i => i * i)));

The example prints the values 1 to 10 using a foreach loop; the sequence is generated with Enumerable.Range. The classic for loop gives more control over the step. The last line squares the numbers 1 to 5 with LINQ.

$ dotnet run
1 2 3 4 5 6 7 8 9 10
10 7 4 1
1,4,9,16,25

C# constants

Unlike variables, constants retain their values. Once initialized, they cannot be modified. Constants are created with the const keyword.

Program.cs
const int Width = 100;
const int Height = 150;
int size = 40;

size = 50;

// Width = 110;       // error CS0131: the left-hand side of an assignment must be a variable

Console.WriteLine(Width * Height);
Console.WriteLine(size);

In this example, we declare two constants and one variable.

const int Width = 100;
const int Height = 150;

We use the const keyword to tell the compiler that we declare a constant. The value must be known at compile time. The naming convention of .NET for constants is PascalCase, as in Width.

// Width = 110;

Changing a constant is not possible. If we uncomment this line, we get a compilation error.

$ dotnet run
15000
50

C# string formatting and interpolation

Building strings from variables is a very common task in programming. C# has the string.Format method for composite formatting, and since C# 6 the string interpolation, which puts the variables directly into the string.

Program.cs
int age = 34;
string name = "William";

string msg = string.Format("{0} is {1} years old.", name, age);
Console.WriteLine(msg);

// interpolation: the variables are inside curly brackets
string msg2 = $"{name} is {age} years old";
Console.WriteLine(msg2);

// expressions and format strings are allowed
double price = 1234.5678;
Console.WriteLine($"{name.ToUpper()} will be {age + 1}; price: {price:F2}, {price:N1}, {price,12:F1}|");

// raw string literal for text with quotes
string json = $$"""
    {"name": "{{name}}", "age": {{age}}}
    """;
Console.WriteLine(json);

In the code example, we build strings in several ways.

string msg = string.Format("{0} is {1} years old.", name, age);

The {0} and {1} are the places where the arguments are evaluated. The numbers are the positions of the arguments. Strings are immutable in C#, so formatting always creates a new string.

string msg2 = $"{name} is {age} years old";

The interpolated string is preceded by the $ character and the expressions are inside curly brackets. It is shorter and safer than composite formatting, since the compiler checks the expressions.

Console.WriteLine($"{name.ToUpper()} will be {age + 1}; price: {price:F2}, {price:N1}, {price,12:F1}|");

Any expression is allowed inside the braces. After a colon, we give a format string: F2 is a fixed-point number with two decimals and N1 uses group separators. After a comma comes the alignment, the minimum width of the field; a positive value right-aligns the text. The output of numbers depends on the current culture.

string json = $$"""
    {"name": "{{name}}", "age": {{age}}}
    """;

A raw string literal (C# 11) can contain quotes and braces without escaping. With $$, the interpolation uses double braces, so the single braces of the JSON stay literal. The indentation of the closing quotes is removed from all lines. See the string format tutorial for more.

$ dotnet run
William is 34 years old.
William is 34 years old
WILLIAM will be 35; price: 1234.57, 1,234.6,       1234.6|
{"name": "William", "age": 34}

Source

A tour of the C# language

In this article we covered some basics of the C# language.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.