C# is a popular programming language that first appeared in 2000. It is mostly an object-oriented language, but also includes some functional features such as lambdas. Originally C# was very similar to Java, but it has evolved in its own way over the past 20+ years.
C# is developed by Microsoft as part of an open-source software package called .NET, which includes the C# compiler and runtime as well as a large collection of built-in libraries. The latest version is .NET 7, which appeared in November 2022 and includes C# 11, the latest version of the C# language.
In this course we'll learn various features of C# found in the language through C# 10. We won't use any features of C# 11. One reason for that is that ReCodEx includes only .NET 6 and C# 10, so if your program uses newer features then it will not work on ReCodEx.
In Programming 1 we learned Python. Some advantages of C# over Python include the following:
C# is much faster. A C# program might typically run 10-20 times as fast as its Python equivalent.
C# is statically typed. That means that every variable (including function parameters) has a fixed type, and can only hold values of that type. This has two major benefits. One is that the compiler can perform type checking, which can find many kinds of bugs at compile time. Another benefit is that it lets the compiler generate much more efficient code, which makes programs faster as we observed just above.
On the other hand, some disadvantages of C# include the following:
C# is more verbose: often you have to type more characters than you would in Python to get the same effect.
C# has no REPL. If you want to experiment with a program, you have to modify its source code and recompile it.
The compiler is a bit slow: compiling even the simplest "hello, world" program takes a second or two.
Go to the .NET home page, then click Download. Then follow the instructions to install either .NET 6 or .NET 7, either of which is adequate for this class.
If you are on a Mac with an ARM processor (e.g. an Apple M1 or M2), be sure to download and install the Arm64 version of the installer, not the x64 version. The Arm64 version will be more efficient on your machine, and the x64 version may not show up in your path after installation. The x64 installer might be selected by default on the download page, in which case you'll need to click the small triangle and select the Arm64 version instead.
After you've installed .NET, the dotnet
program
should be available in your path so that you can run it from the
terminal:
$ dotnet --version 6.0.104 $
To create a new C# project, first create an empty directory. It can have any name you like – let's suppose it's called "hello". Then open a terminal window in that directory, and run
$ dotnet new console
That will create a couple of files including Program.cs and hello.csproj.
Now open the directory in an IDE. I recommend using Visual Studio Code. You may see a message "The 'C#' extension is recommended for this file type". If so, click the Install button under the message. Visual Studio Code will install the extension that provides C# support. Furthermore, you will see a message "Required assets to build and debug are missing. Add them?". Click the Yes button under the message.
(As an alternative to the above, you can perform the steps in a different order. Create an empty directory, and open it in Visual Studio Code. Then press Ctrl + ` to open a terminal window inside Visual Studio Code, and run "dotnet new console" inside that terminal. The result will be the same.)
Let's look at the file Program.cs created by "dotnet new console":
Console.WriteLine("Hello, World!");
The program calls WriteLine(), which is a static method of the Console class. Notice that the string "Hello, World!" is enclosed in double quotes. You must use these for multi-character strings in C#. Also notice that this statement, like every statement in C#, ends with a semicolon.
Let's run the program. Open a terminal window in the project directory (in Visual Studio you can do so by typing Ctrl+Shift+C). Then type
$ dotnet run
That will compile the program and run it, producing the
expected output:
Hello, World!
The one-line program in the previous section seems simple enough. Alas, if you submit it to ReCodex then it will fail to compile, with error messages such as these:
error CS8804: Cannot specify /main if there is a compilation unit with top-level statements. Program.cs(1,1): error CS0103: The name 'Console' does not exist in the current context
What is wrong? Actually there are two problems.
The first is that this program contains top-level code, i.e. code that is not inside a method in a class. This is a relatively new feature in C# (it first appeared in C# 9 in 2020), and for technical reasons is not supported on ReCodEx.
The second problem is that this program uses an implicit namespace, namely the System namespace that includes the Console class. Usually in C# when you want to use a class in any namespace, you must import that namespace via a "using" statement. However, certain namespaces including System are automatically (i.e. implicitly) available – you don't have to import them. And so we were able to call Console.WriteLine() without importing System. This is another relatively new feature in C#, and for technical reasons is not supported on ReCodEx.
So if we plan to submit our program to ReCodEx, we'll need to write it differently:
using System; class Hello { static void Main() { Console.WriteLine("Hello, World!"); } }
The name "Main" is special: it denotes the top-level entry point to a C# program. There can be only one class with a Main method in your entire program.
In the program above, Visual Studio Code will display the line "using System;" in gray. If you hover over it, you'll see a message "Unnecessary using directive". That's because on the local machine the System namespace is automatically available.
If you're writing a program that you intend to submit to ReCodEx, I recommend that you disable implicit namespaces in your project's .csproj file:
<ImplicitUsings>disable</ImplicitUsings>
With that change, the line "using System;" will be required, so Visual Studio Code won't gray it out. More generally, you will need to write a using statement for any namespace that you use, which is consistent with ReCodEx's expectations.
To start writing code in C# we'll need to know about various built-in types. First, here are several predefined integral types:
int – a signed 32-bit integer (-231 to 231 – 1)
long – a signed 64-bit integer (- 263 to 263 – 1)
byte – an unsigned 8-bit integer (0 to 255)
C# includes many more integer types of various fixed sizes, but the ones listed here are enough for our purposes today.
A variable declaration declares one or more variables. Each variable must have a type:
int i; long j, k;
An assignment statement assigns a value to a variable:
i = 14; j = 1000;
It's possible to combine a declaration and assignment into a single statement:
int x = 10; int y = 20, z = 30; x = 40;
As you might expect, the line "x = 40" modifies x, changing it from 10 to 40.
Notice that an integer constant may contain embedded underscores for readability:
int i = 1_000_000_000;
A single-line comment begins with //
and extends to
the end of the line:
int x = 1000; // one thousand
Comments delimited with /*
and */
can
extend over multiple lines:
/* this is a comment with multiple lines */
Note that in C# (unlike Python) basically ignores whitespace. To be more precise, all sequences of whitespace (including newlines) are equivalent to a single space. So you can arrange characters onto lines however you like. For example, the following line is valid, though it is not great style:
int x = 10; int y = 20; x = 30; y = 40;
C# includes the arithmetic operators +
(addition), -
(subtraction), *
(multiplication), /
(division) and %
(remainder). There is no operator specifically for integer division
(like //
in Python). Instead, the /
operator performs integer division if both its arguments have integer
types:
Console.WriteLine(7 / 3); // will write 2
(In the next lecture, we'll learn about floating-point types and will see that this operator can also perform floating-point division.)
The result of integer division is truncated toward zero. For example, -17 / 5 is -3. (This differs from some other languages such as Python, which truncates toward -∞. In Python, -17 // 5 is -4.)
The result of the % operator is consistent with integer division. For example, -17 % 5 is -2, because
-17 = 5 * (-3) + (-2)
(This is also different from Python, in which, x % 5 will always be in the range from 0 .. 4.)
C# also includes the compound assignment operators +=
,
-=
, *=
, /=
,
and %=
. They work just like in Python:
int x = 10; x += 5; // now x is 15 x *= 2; // now x is 30
As we saw above, integral types in C# have a fixed size. The compiler will not allow us to declare a constant that is out of bounds:
int x = 2_000_000_000; // OK int y = 3_000_000_000; // error at compile time
What will happen if we perform arithmetic that goes out of bounds? Let's try it:
int x = 2_000_000_000; x += 1_000_000_000; Console.WriteLine(x);
This program will print
-1294967296
This is an example of arithmetic overflow. The value wrapped past the maximum value of 232 – 1, back into the range of negative integers. The actual value that was printed is
3,000,000,000 – 232
In summary, C#'s fixed-range integers are efficient, but we see that they come at a cost: integer overflow may produce invalid results.
The bool
type represents a Boolean value, namely either true
or false
.
(These constants are not capitalized as they were in Python.)
bool
b
=
true
;
bool
c
=
false
;
The type char
represents a 16-bit Unicode character. A character constant is
enclosed in single quotes, e.g. 'x'
or 'ř'
.
The type string
represents an immutable sequence
of characters. A string constant is enclosed in double quotes,
e.g. "hello"
.
C# includes the relational operators ==
(equals), !=
(does not equal), <
(less than), <=
(less than or equal
to), >
(greater than), >=
(greater than or equal to). All of these names are just like in
Python. Each of these operators produces a value of type bool.
The equality operators == and != will work with any of the types we've seen so far. The other comparison operators work with integral types and characters (but not bools or strings).
An if
statement executes a statement if a condition
is true. If there is an else
clause, it is executed if
the condition is false. For example:
if (i > 0) Console.WriteLine("positive"); else Console.WriteLine("negative");
Notice that the condition in an if
statement must always
be surrounded by parentheses.
Either the 'if' or 'else' clauses may contain multiple statements, surrounded by braces. For example:
if (i > 0) { Console.WriteLine("positive"); Console.WriteLine("greater than zero"); } else { Console.WriteLine("negative"); Console.WriteLine("not greater than zero"); }
If you wish, you may even surround a single statement by braces. For
example, the first if
statement above could be written
if (i > 0) { Console.WriteLine("positive"); } else { Console.WriteLine("negative"); }
Whether to use braces in this situation is a question of style.
C# includes the boolean operators !
(not), ||
(or), &&
(and). For example:
if (!(0 <= x && x < 10)) WriteLine("out of range");
A while
loop iterates as long as a condition is true.
Its body may contain either a single statement, or (more typically) a
group of statements surrounded by braces:
i = 1; while (i < 10) { sum = sum + i; i += 1; }
Notice that the condition in an while
statement must
always be surrounded by parentheses.
C# includes a special value null
,
which is like None in Python. It represents the absence of a value.
Most types cannot hold a null value:
int x = null; // error: cannot convert null to int
However, you can add the suffix ?
to any type to make it
nullable. For example, int?
is a type that holds
either an int, or null:
int? x = null; int? y = 7;
The Console.ReadLine() method reads a line
of standard input. It returns a value of type string?
,
which is either a string, or is null (in the case that no more input
is available).
So we can write
string? s = Console.ReadLine(); if (s == null) Console.WriteLine("no more input"); else Console.WriteLine(s);
To keep things simple, often we don't want to worry about the null
case. We can use the null-forgiving operator ! to convert from
the nullable type string?
to the type string
, which cannot be null:
string s = Console.ReadLine()!;
This operator is like an assertion that the value will not be null. If it actually is null at run time, the program will fail with an exception!
The function int.Parse() can convert a string to an integer.
So we can read an integer on a single line like this:
int i = int.Parse(Console.ReadLine()!);