1

Introducing C#

The C# programming language can be used to build software components and applications that run on a wide variety of operating systems (platforms)—including mobile devices, game consoles, web applications, Internet of Things (IoT), microservices, and desktop applications. Furthermore, C# is free; in fact, it is entirely open source, so you can view, modify, redistribute, and contribute back any improvements you make. As a language, C# is built on features found in its predecessor C-style languages (C, C++, and Java), making it immediately familiar to many experienced programmers.1

This chapter introduces C# using the traditional HelloWorld program. It focuses on C# syntax fundamentals, including defining an entry point into the C# program, which will familiarize you with the C# syntax style and structure and enable you to produce the simplest of C# programs. Prior to the discussion of C# syntax fundamentals is a summary of managed execution context, which explains how a C# program executes at runtime. This chapter ends with a discussion of variable declaration, writing and retrieving data from the console, and the basics of commenting code in C#.

Hello, World

The best way to learn a new programming language is to write code. The first example is the classic HelloWorld program. In this program, you will display some text to the screen.

Listing 1.1 shows the complete HelloWorld program; in the following sections, you will compile and run the code.

Listing 1.1: HelloWorld in C#2
Console.WriteLine("Hello. My name is Inigo Montoya.");

(A listing this simple requires a feature—top-level statements—enabled in C# 9.0 to help with learning C#. An alternative listing—arguably a more typical listing—is shown later in Listing 1.6. See Chapter 4 for more information about top-level statements.)

Beginner Topic
Basic Compilation Terms

A compiler acts like a translator, changing code from one language to another. Generally, the compiler is responsible for converting from a higher level language, like C#, to a lower level language that a computer understands directly. In the case of C#, the compiler output is an intermediate language that a second compiler translates to machine language. This is discussed further in the “Managed Execution and the Common Language Infrastructure” section later in this chapter. Source code is simply the text that makes up a program, so Listing 1.1 is considered source code to our HelloWorld Program. The word code is often used interchangeably with source code.

Creating, Editing, Compiling, and Running C# Source Code

Once you have written your C# code, it is time to compile and run it. Based on your operating system, you have a choice of which compiler to download. Generally, the implementation is packaged into a software development kit (SDK). The SDK includes the compiler, the runtime execution engine, the framework of pragmatically accessible functionality that the runtime can access (see “Application Programming Interface” later in the chapter), and any added tooling (such as a build engine for automating build steps) that might be bundled with the SDK. Given that there are compilers available for multiple platforms and that C# has been publicly available since 2000 (see “Multiple .NET Frameworks” later in the chapter), there are several options to choose from.

For each operating system the installation instructions vary. For this reason, we recommend you visit https://dotnet.microsoft.com/download for download and installation instructions, selecting the package to download based on which operating system you will be developing on. Furthermore, you have a choice of which .NET implementation(s) to use—sometimes referred to as the .NET framework(s). While we could provide further details here, the .NET download site has the most updated instructions for each combination supported. While there are multiple framework versions available, the easiest is to download the default one, which corresponds to the latest fully released version.

There are also numerous ways to edit your source code, including the most rudimentary of tools, such as Notepad on Windows, TextEdit on Mac/macOS, or vi on Linux. However, you’re likely to want something more advanced so that at least your code is colorized. Any programming editor that supports C# will suffice. If developing on Linux, we recommend you consider the open source editor Visual Studio Code (https://code.visualstudio.com). To optimize working with C# in Visual Studio Code, you will want to install the C# extension, as shown in Figure 1.1. However, if you are working on Windows or Mac, consider the corresponding version of Microsoft Visual Studio 2022 (or later)—see https://visualstudio.microsoft.com/. All are available free of charge.

Figure 1.1: Installing the C# extension for Visual Studio Code

In the remainder of this section, we provide instructions for these editors. For Visual Studio Code, we rely on the command-line interface (CLI) tool dotnet CLI for creating the initial C# program in addition to compiling and running the program. For Windows and Mac, we focus on using the platform-specific version of Visual Studio 2022.

With Dotnet CLI

The dotnet command, dotnet, is the dotnet command-line interface, or dotnet CLI, and it may be used to generate the initial code base for a C# program in addition to compiling and running the program.3 (To avoid ambiguity between CLI referring to the Common Language Infrastructure or the command-line interface, throughout the book we will prefix CLI with dotnet when referring to the dotnet CLI. CLI without the dotnet prefix refers to Common Language Infrastructure.) Once you have completed the installation, verify that dotnet is an available command from the terminal—thus verifying your installation.

Following are the instructions for creating, compiling, and executing the HelloWorld program from a terminal on Windows, macOS, or Linux:

1.
Open the terminal. (Optionally, consider using the cross-platform command-line interface PowerShell by running the command pwsh.4)
2.
Create a new directory where you want to place the code. Consider a name such as HelloWorld or EssentialCSharp/HelloWorld. From the command line, use
mkdir HelloWorld
3.
Navigate into the new directory so that it is the terminal’s current location.
cd HelloWorld
4.
Execute dotnet new console to generate the initial scaffolding (or project) for your program. While several files are generated, the two main files are Program.cs and the project file HelloWorld.csproj:
dotnet new console
5.
Run the generated program. This compiles and runs the code created by the dotnet new console command. The content of Program.cs is similar to Listing 1.1 but it outputs “Hello World!” instead.
dotnet run
6.
Even though we don’t explicitly request the project to compile (or build)—via the dotnet build command, that step still occurs implicitly.
7.
Edit the Program.cs file and modify the code to match what is shown in Listing 1.1. If you use one of the editors mentioned to open and edit Program.cs, you will see the advantage of a C#-aware editor, as the code will be colorized to indicate the different types of constructs in your program. To open and edit using Visual Studio Code, use the following command or start Visual Studio Code and open the Program.cs file.
code .
8.
(Alternatively, Output 1.1 shows an approach using only the command line that works for Bash and PowerShell.)
9.
  Rerun the program:
dotnet run

Output 1.1 shows the output following the preceding steps.5

Output 1.1
1>
2> mkdir ./HelloWorld
3> cd ./HelloWorld/
4> dotnet new console
The template "Console Application" was created successfully.
Processing post-creation actions...
Running 'dotnet restore' on C: \EssentialCSharp\HelloWorld\HelloWorld.csproj...
  Restore completed in 100.38 ms for C:\EssentialCSharp\HelloWorld\HelloWorld.csproj.
Restore succeeded.
5> dotnet run
Hello World!
6> echo '
Console.WriteLine("Hello. My name is Inigo Montoya.");
' > Program.cs
7> dotnet run
Hello. My name is Inigo Montoya.
With Visual Studio 2022 (Windows or Mac)

With Visual Studio 2022, which runs only on Microsoft Windows or Mac, the procedure is similar, but instead of using the command line, you use an integrated development environment (IDE), which has menus you can choose from rather than executing everything from the command line:

1.
Launch Visual Studio 2022.
2.
Click the Create a new project button. (If the Start Window is not visible, you can open it from the File->Start Window menu or jump directly to create the project via the File->New Project (Ctrl+Shift+N) menu.)
3.
From the Search box (Alt+S), type Console App and select the Console App item (see Figure 1.2). (You can optionally select C# to reduce the options count if other languages are installed.)
Figure 1.2: The Create a new project dialog
4.
For the Project name text box, use HelloWorld, and for Location, select a working directory of your choosing (see Figure 1.3).
Figure 1.3: The Configure your new project dialog
5.
At the Additional information dialog, choose .NET 7.0 in the Framework dropdown. (Leave the Do not use top-level statements checkbox unchecked.)
6.
Once the project is created, you should see a Program.cs file, as shown in Figure 1.4.

Figure 1.4: Dialog that shows the Program.cs file
7.
Run the generated program using the Debug->Start Without Debugging (Ctrl+F5) menu. This displays the terminal with the text shown in Output 1.2 except the first line displays “Hello World!” only.
Output 1.2
Hello. My name is Inigo Montoya.
...\HelloWorld.exe (process 11856) exited with code 0.
Press any key to close this window . . .
8.
Modify Program.cs to match Listing 1.1. Rerun the program to see the output shown in Output 1.2.
Understanding a Project

Whether using dotnet CLI or Visual Studio, there are several files created. The first file is a C# file with the name Program.cs by convention. The name Program is commonly used as the starting point for a console program, even though any name could be used. The .cs extension is the standard convention for all C# files and what the compiler expects to compile into the final program by default. To use the code shown in Listing 1.1, open the Program.cs file and replace its content with Listing 1.1. Before saving the updated file, observe that the only functional difference between Listing 1.1 and what was generated by default is the text between the double quotes.

A configuration file called a project file is included as part of the generated source code of your C# project. The project file content varies from one application type and .NET framework to the next. However, at a minimum, it generally identifies what application type to build (console, web, library, etc.), which .NET framework(s) to support, compiler settings, and which potential settings are needed to launch the application, along with other dependencies the code may rely on (called libraries). For example, the simple .NET console application project file created in the previous section appears in Listing 1.2.

Listing 1.2: Sample .NET Console Project File
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
  </PropertyGroup>
</Project>

In Listing 1.2, the application type is identified as a .NET 8.0 (net8.0) console application (Exe). The two other elements, Nullable (C# 8.0) and ImplicitUsings (C# 10.0) , will be discussed in “Declaring Types That Allow Null” in Chapter 3 and “Using Directives” in Chapter 5, respectively. All other settings (such as which C# files to compile) are identified by convention. For example, by default, all *.cs6 files in the same directory (or subdirectory) as the project file are included in the compile.

Compilation and Execution

When you execute dotnet run, it first implicitly runs dotnet build to compile the code. The compiled output created by the dotnet build command is an assembly called HelloWorld.dll.7 Assemblies contain a set of instructions specifying how a program will behave. The extension stands for dynamic link library (DLL), and with .NET, assemblies have a .dll extension even if they are console programs, as this one is. (On Windows, an .exe file is also created.) By default, the compiled output for a .NET application is placed into a subdirectory according to the TargetFramework identified in the project file, as shown in Listing 1.2 (./bin/Debug/net7.0/). The Debug directory is used because the default configuration is debug. This configuration causes the output to be optimized for debugging rather than for performance. The compiled output does not execute on its own. Rather, it needs the CLI to host the code. For .NET applications, this requires using the dotnet.exe (dotnet on Linux and Mac) process as a host process for the application. Hence why the program is executed with the dotnet run command. That said, there is a way to generate a stand-alone executable that includes the necessary runtime files so that installing the dotnet runtime is not required—see the “Advanced Topic: Publishing a Stand-Alone Executable” (On Windows, the .exe file can be used directly, if the dotnet runtime is installed, rather than using dotnet run.)

Essential C# Source Code

Both the source code and the manuscript text are available at https://essentialcsharp.com. Alternatively, the source code for this book is available for download on GitHub directly at https://github.com/IntelliTect/EssentialCSharp. Instructions for compiling and running the code are available in the README.md file at the same location.

An alternative approach is to paste the source code into the HelloWorld program created earlier in the chapter and then execute the source code.

________________________________________

1. The first C# design meeting took place in 1998.
2. Refer to the movie The Princess Bride if you’re confused about the Inigo Montoya references.
3. This tool was released around the same time as C# 7.0, and it eclipsed compiling directly with the C# compiler, csc.exe.
5. The bold formatting in an Output indicates the user-entered content.
6. The “*” in *.cs is called a wildcard character, and matches any number of characters including none. In this instance, this identifies that any file ending in .cs will be included. If it was i*.cs it would include any files starting with an i and ending in .cs.
7. Note that if you use the Microsoft .NET Framework to create a console program, the compiled code is placed into a HelloWorld.exe file that you can execute directly assuming the Microsoft .NET Framework is installed on the computer.
{{ snackbarMessage }}
;