Intro

C# (pronounced C-Sharp, like the musical note) is a programming language loosely based on C that was developed by Microsoft in 2000.

This C# tutorial is aimed at students who have previously coded primarily in Python.

Throughout this tutorial, you will see a Python program, and then the equivalent C# program.

Get Started

Firstly, you need to download a C# compiler. To do this, first download Visual Studio and then add the C# extension.

Alternatively, you can use an online compiler like .NET Fiddle.

Hello, World!

Let's start with the basic "Hello, World!" program. In Python, it's only one line:

# Python
print("Hello, World!")

But in C# it's a bit more complicated.

// C#
using System;

namespace PrintHelloWorld {
  class MyProgram {
    static void Main(string[] args) {
      Console.WriteLine("Hello, World!");    
    }
  }
}

Let's unpack this. The line Console.WriteLine("Hello, World!"); is what's actually outputting the text.

Everything else is what's referred to as the "boilerplate": it's just there because that's how the language works. Almost every C# program will need this boilerplate.

In C#, code is organised using namespaces and classes. Inside the class, we have a Main function. The static void that comes before it shows that the function will return nothing (void).

Also, you may have noticed the semicolon at the end of the line. This is necessary in C#, and the program will not run if you don't have semicolons separating lines.

Output

You have seen the Console.WriteLine() method in the previous example. There is also a Console.Write() method which outputs some text without a trailing newline.

This is equivalent to using Python's print() function using end="".

# Python
print("This is all ", end="")
print("on the same line!", end="")
// C#
Console.Write("This is all ");
Console.Write("on the same line!");

Output:

This is all on the same line!

Note: the C# example here is missing the boilerplate. From now on, the boilerplate will not be displayed in any C# example.

Input

The C# equivalent of Python's input function is the Console.ReadLine() method.

# Python
name = input("Enter your name: ")
print("Hello " + name)
// C#
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine("Hello " + name);
            

Just like with input, Console.ReadLine() will always return a string.

Comments

Python supports two types of comments, one of which is not supposed to be used as a comment.

# Python

# This is a single-line comment.
# Each line starts with a hashtag/octothorpe.

"""This is a docstring (technically not a multi-line comment),
but it can be used as a multi-line comment.
It starts and ends with three quotes
(single or double, but start and end must match)."""

C#, like many other programming languages, fully supports single-line and multi-line comments.

// C#

// This is a single-line comment.
// Each line starts with two forward-slashes.

/* This is a multi-line comment.
It starts with a slash and an asterisk,
and ends with an asterisk and a slash. */

/**********************
 *  You can even do   *
 * some cool patterns *
 * with these multi-  *
 *  line comments :D  *
 **********************/

Data Types

Here are the basic data types in C#.

// C#

int  // A 32-bit integer
     // Stores whole numbers between -2^31 and +2^31

long  // A 64-bit integer
      // Stores whole numbers between -2^63 and +2^63

float  // A single-precision (32-bit) floating point
       // Stores fractional numbers with single-precision

double  // A double-precision (64-bit) floating point
        // Stores fractional numbers with double-precision

char  // A single character
      // Surrounded by single quotes

string  // A collection of characters
        // Surrounded by double quotes

bool  // A true or false value
      // Use lowercase: true and false

Firstly, integers don't actually have a limit in Python, but they do in C#. You will mostly need to use int, but in some cases (where your number goes above 2^31), you may need to use long.

Secondly, Python's float is equivalent to C#'s double. Python doesn't have a data type for single-precision floats, but C# does. In any case, it will probably be better to use double for the extra precision.

Thirdly, Python does not have a separate data type for a single character, but C# does. In Python, single and double quotes are interchangeable, but in C#, you must use single quotes for chars and double quotes for strings.

And finally, in Python, the boolean values are True and False. In C#, they are lowercased: true and false.

Variables

C# is a "statically typed" language, meaning that variables cannot change data type. You must state the type of each variable when it is declared.

Declaring a variable in C# is easy: you can just state the type and then declare it just like in Python.

// C#
string text = "Hello, World!";
int age = 16;

Assigning a new value to an existing variable is the same as Python.

// C#
int age = 16;
Console.WriteLine(age);  // Outputs 16

age = 17;
Console.WriteLine(age);  // Outputs 17

Constants

C# also supports constants, which are variables that cannot be changed. To declare a constant, just add the keyword const in front of the declaration.

// C#
const double PI = 3.141592653589793;
Console.WriteLine(PI);  // Outputs 3.141592653589793

If you try to change the value of a constant, the program will error.

Type Casting

In Python, you can convert between types using the type name.

# Python
num1 = 12.34
print(num1)  # 12.34

num2 = int(num2)
print(num2)  # 12

In C#, you can do a similar thing.

// C#
double num1 = 12.34;
Console.WriteLine(num1);  // 12.34

int num2 = (int) num1;
Console.WriteLine(num2);  // 12

Operations

In C#, addition, subtraction, and multiplication work the same way as in Python.

However, division and modulus work a bit differently.

# Python
a = 5
b = 2
print(a // b)  # 2
print(a / b)  # 2.5
// C#
int a = 5;
int b = 2;
Console.WriteLine(a / b);  // 2

double c = 5;
int d = 2;
Console.WriteLine(c / d);  // 2.5

C# does not have a separate integer division operator. Instead, if both operands are integers, it automatically performs integer division. If at least one operand is a float, it performs normal division.

# Python
print(15 % 6)  # 3
print(-15 % 6)  # 3
// C#
Console.WriteLine(15 % 6);  // 3
Console.WriteLine(-15 % 6);  // -3

The result of a modulus in Python will always be nonnegative, but it can be negative in C#.

Also, C# has the ++ (increment) and -- (decrement) operators.

# Python
num = 123
num -= 1
print(num)  # 122
// C#
int num = 123;
num--;
Console.WriteLine(num);  // 122

And finally, the logical operators are also different in C#.

# Python
a and b
a or b
not a
// C#
a && b
a || b
!a

Braces

Instead of Python's indentation, C# (along with many other languages in the C family) uses braces.

# Python
if a > b:
    print("Yay")
// C#
if (a > b) {
    Console.WriteLine("Yay");
}

If Statements

Apart from braces vs indentation, the only other differences are that C# uses else if instead of elif, and the parentheses around the condition are required in C#.

# Python
if condition:
    ...
elif condition:
    ...
else:
    ...
// C#
if (condition) {
    // ...
} else if (condition) {
    // ...
} else {
    // ...
}

C# also has a ternary operator just like Python.

# Python
result = x if condition else y
// C#
int result = condition ? x : y;

Note that the order is different.

Switch-Case

C#'s switch-case statements work similarly to Python's match-case statements (introduced in 3.10).

// C#, using if-else
if (x == 1) {
    // ...
} else if (x == 2) {
    // ...
} else if (x == 3) {
    // ...
} else if (x == 4) {
    // ...
} else {
    // ...
}
// C#, using switch-case
switch (x) {
    case 1:
        // ...
        break;
    case 2:
        // ...
        break;
    case 3:
        // ...
        break;
    case 4:
        // ...
        break;
    default:
        // ...
}

Remember to add in the breaks!

While Loops

While loops in C# are the same as in Python, except that they use parentheses and braces (like if statements).

# Python
while condition:
    ...
// C#
while (condition) {
    // ...
}

Arrays

Arrays in C# are similar to lists in Python, but they have one main difference: all elements of an array must be of the same type.

You define an array using braces instead of square brackets. Also, you need to put empty square brackets after the type.

# Python
num_list = [2, 3, 5, 7, 11]
// C#
int[] num_list = {2, 3, 5, 7, 11};

Use two sets of empty square brackets for nested (2D) arrays.

# Python
nested_list = [[1, 2], [3, 4]]
// C#
int[][] nested_list = {{1, 2}, {3, 4}};

ForEach Loops

ForEach in C# is the equivalent of Python's for loop. It iterates through each element in an array.

# Python
for num in num_list:
    ...
// C#
foreach (int num in num_list) {
    // ...
}

For Loops

The for loop in C# is sort of like a while loop. These two C# examples both output the whole numbers from 1 to 10.

// C#
int i = 1;
while (i <= 10) {
    Console.WriteLine(i);
    i++;
}
// C#
for (int i = 1; i <= 10; i++;) {
    Console.WriteLine(i);
}

The for loop is made up of three statements. The first is executed once before the loop begins. The second is the condition for the loop. And the third is executed at the end of each run through.

You will use the for loop a lot, as it replaces Python's for i in range(...) construct.

FizzBuzz

We're now ready to do an example program of FizzBuzz.

The Python example is given below. See if you can write your own C# code before you look at the program provided here.

# Python
for i in range(1, 100):
    if i % 3 == 0:
        if i % 5 == 0:
            print("FizzBuzz")
        else:
            print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Here's the C# example:

// C#
for (int i = 1; i <= 100; i++;) {
    if (i % 3 == 0) {
        if (i % 5 == 0) {
            Console.WriteLine("FizzBuzz");
        } else {
            Console.WriteLine("Fizz");
        }
    } else if (i % 5 == 0) {
        Console.WriteLine("Buzz");
    } else {
        Console.WriteLine(i);
    }
}

As an additional challenge, how small can you make it? I got my solution to just 84 characters.

// C#
for(int i=0;i++<100;)Console.WriteLine((i%3<1?"Fizz":"")+(i%5<1?"Buzz":i%3<1?"":x));

Try it online here. Note: this solution requires the latest version of C#.