03_C#_01
03_C#_01
Building C# Applications
As a C# programmer, you can choose from among numerous tools to build .NET Core applications. The tool
(or tools) you select will be based primarily on three factors: any associated costs, the OS you are using to
develop the software, and the computing platforms you are targeting. The point of this chapter is to provide
the information you need to install the .NET 6 SDK and runtime and to present a first look at Microsoft’s
flagship IDEs, Visual Studio Code and Visual Studio.
The first part of this chapter will cover setting up your computer with the .NET 6 SDK and runtime.
The next section will examine building your first C# application with Visual Studio Code and Visual Studio
Community Edition.
■■Note The screenshots in this and subsequent chapters are from Visual Studio Code v 1.61.2 or Visual
Studio 2022 Community Edition v17.0.0 on Windows. If you want to build your applications on a different OS or
IDE, this chapter will guide you in the right direction; however, the look and feel of your IDE might differ from the
various screenshots in this text.
Installing .NET 6
To get started developing applications with C# 10 and .NET 6 (on Windows, macOS, or Linux), the .NET 6
SDK needs to be installed (which also installs the .NET 6 runtime). All of the installs for .NET and .NET Core
are located at the convenient www.dot.net. On the home page, click Download and then click “All .NET
downloads” under .NET. After clicking “All .NET downloads,” you will see the LTS versions of .NET (6.0) and
a link for .NET 6.0. Click “.NET 6.0 (recommended).” Once on that page, select the correct .NET 6 SDK for
your operating system. For this book, you will need to install the SDK for .NET Core version 6.0.100 or higher,
which also installs the .NET and ASP.NET Core runtimes. If you are using a Windows machine, it will also
install the .NET Desktop runtime.
The --version option displays the highest version of the SDK installed on your machine, or the version
specified in a global.json located at or above your current directory. Check the current version of the .NET
SDK installed on your machine, enter the following:
dotnet --version
dotnet --list-runtimes
dotnet --list-sdks
28
Chapter 2 ■ Building C# Applications
C
hecking For Updates
New with .NET 6, the CLI has a new command that checks your installed versions of the .NET/.NET Core
SDKs and runtimes for updates. This command is backwards compatible, so it also checks for updates for
.NET Core 3.1. It will also inform you if any of the installed SDK or runtimes are out of support (like the 2.x
versions). To check the versions, enter the following command:
The command will not update any of the versions for you, it just reports the status. To update, follow the
same procedure outlined above to download and install the new version(s).
{
"sdk": {
"version": "5.0.400"
}
}
Running dotnet.exe --version in this directory (or any subdirectory) will return 5.0.400.
29
Chapter 2 ■ Building C# Applications
The Community and Professional editions are essentially the same. The most significant difference
is in the licensing model. Community is licensed for open source, academic, and small-business uses.
Professional and Enterprise are commercial products that are licensed for any development, including
enterprise development. As one would expect, the Enterprise edition has many additional features
compared to the Professional edition.
■■Note For specific licensing details, please go to www.visualstudio.com. Licensing Microsoft products
can be complex, and this book does not cover the details. For the purposes of writing (and following along with)
this book, Community is legal to use.
All Visual Studio editions ship with sophisticated code editors, integrated debuggers, GUI designers for
desktop applications, and much more. Since they all share a common core set of features, the good news is
that it is easy to move between them and feel quite comfortable with their basic operation.
■■Note You can download Visual Studio 2022 Community from www.visualstudio.com/downloads.
The Visual Studio 2022 installation process is now broken down into application-type workloads. This
allows you to install just the components you need for the type of applications you plan on building. For
example, if you are going to build web applications, you would install the “ASP.NET and web development”
workload.
Another (extremely) significant change is that Visual Studio 2022 supports true side-by-side installation.
Note that I am not referring to just previous versions of Visual Studio but to Visual Studio 2022 itself! For
example, on my main work computer, I have Visual Studio 2022 Enterprise installed for my professional
work and Visual Studio 2022 Community for use in my books, courses, and conference lectures. If you have
Professional or Enterprise supplied by your employer, you can still install the Community edition to work on
open source projects (or the code in this book).
When you launch the installer for Visual Studio 2022 Community, you are presented with the
screen shown in Figure 2-1. This screen has all of the workloads available, the option to select individual
components, and a summary on the right side showing what has been selected.
30
Chapter 2 ■ Building C# Applications
For this book, you will want to install the following workloads:
• .NET desktop development
• ASP.NET and web development
• Data storage and processing
On the “Individual components” tab, also select Class Designer and Git for Windows (all under “Code
tools”). Once you have all of them selected, click Install. This will provide you with everything you need to
work through the examples in this book.
31
Chapter 2 ■ Building C# Applications
Select the “Create a new project” option, and you will be prompted with the “Create a new project”
dialog. As shown in Figure 2-3, recently used templates (if any) are on the left, and all available templates are
on the right, including a set of filters and a search box.
32
Chapter 2 ■ Building C# Applications
To start, create a new Console App, making sure to select the C# version and not the Visual Basic
version.
The next screen is the “Configure your new project” dialog, as shown in Figure 2-4. Enter
SimpleCSharpConsoleApp for the project name and select a location for the project. The wizard will also
create a Visual Studio solution, by default named after the project name.
33
Chapter 2 ■ Building C# Applications
■■Note Creating solutions and projects can also be accomplished using the .NET Core Command Line
Interface (CLI). This will be covered with Visual Studio Code.
The next screen prompts for the version of .NET to use. Make sure “.NET 6.0 (Long-term support)” is
selected, as shown in Figure 2-5.
34
Chapter 2 ■ Building C# Applications
Once the project has been created, you will see that the initial C# code file (named Program.cs) has
been opened in the code editor. The initial template just has a comment (the line starting with //) and a
single line of code that writes “Hello, World!” to the console:
Those two lines of code are referred to as top level statements and serve as the entry point into the
application. The next chapter covers top level statements and application entry points in detail. For now,
realize that this is where the execution starts for your app, and ends when all of the lines have executed.
Replace the comment and the single line of code with the following:
■■Note You will notice as you type, Visual Studio attempts to complete the words for you. This is called
IntelliSense (code completion help) and is integrated into Visual Studio and Visual Studio Code.
Here, you are using the Console class defined in the System namespace. The System namespace is
included as part of the global implicit using statements, so it isn’t explicitly needed. This program does not
do anything too interesting; however, note the final call to Console.ReadLine(). This is in place simply to
ensure the user must press a key to terminate the application. With Visual Studio 2022, this is unnecessary as
the VS debugger will pause the program and prevent it from exiting. If you were to navigate to the compiled
version and run it, the program would disappear almost instantly when debugging the program!
■■Note If you want to change the VS debugging experience to automatically end the program, select Tools ➤
Options ➤ Debugging ➤ Automatically close the console when debugging stops.
35
Chapter 2 ■ Building C# Applications
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
To change the .NET version to version 5, for example, simply change the TargetFramework value to
net5.0, as shown here:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
You can also change the target framework by right-clicking the project name in Solution Explorer and
selecting Properties, opening the Application tab, and updating the Target Framework value, as shown in
Figure 2-6.
Using C# 10 Features
In versions of .NET and the .NET Framework, the version of C# supported by a project could be changed.
Since the release of .NET Core 3.0 (and each subsequent.NET version), the version of C# used is tied into
the .NET Core/.NET version. For .NET 6.0 projects, the language version is locked into C# 10. Table 2-2 lists
the target frameworks (.NET, .NET Core, .NET Standard, and .NET Framework) and the default C# version
utilized.
■■Note .NET applications can also be compiled and executed using the CLI. To run your project, enter
dotnet run in the same directory as the project file (SimpleCSharpApp.csproj in this example). The
dotnet run command also automatically builds the project.
If you need to debug your code (which will certainly be important when building larger programs), your
first step is to set breakpoints at the code statement you want to examine. Although there is not much code
in this example, set a breakpoint by clicking the leftmost gray bar of the code editor (note that breakpoints
are marked with a red dot icon; see Figure 2-7).
37
Chapter 2 ■ Building C# Applications
If you now press the F5 key (or use the Debug ➤ Start Debugging menu option or click the green arrow
with Start next to it in the toolbar), your program will halt at each breakpoint. As you would expect, you can
interact with the debugger using the various toolbar buttons and menu options of the IDE. Once you have
evaluated all breakpoints, the application will eventually terminate once the statements have completed.
■■Note Microsoft IDEs have sophisticated debuggers, and you will learn about various techniques over the
chapters to come. For now, be aware that when you are in a debugging session, a large number of useful
options will appear under the Debug menu. Take a moment to verify this for yourself.
■■Note Be aware that when you select the solution in the Solution Explorer window, the IDE’s menu system
will show you a different set of choices than when you select a project. If you ever find yourself wondering
where a certain menu item has disappeared to, double-check you did not accidentally select the wrong node.
38
Chapter 2 ■ Building C# Applications
■■Note This book only uses the Class Diagram tool occasionally to accentuate certain concepts. It is shown
here for completeness, and the choice to use it or the text editor is entirely up to you. The overwhelming
majority of the examples use the text editor of Visual Studio/Visual Studio Code.
To access the visual class designer tools, the first step is to insert a new class diagram file. To do so,
select project in the Solution Explorer, then activate the Project ➤ Add New Item menu option and locate the
Class Diagram type (Figure 2-8).
Figure 2-8. Inserting a class diagram file into the current project
Initially, the designer will be empty; however, you can drag and drop files from your Solution Explorer
window on the surface or right click on the design surface to create new classes. To get started, create a
new class in your project by right clicking on the project and selecting Add ➤ Class. In the Add New Item –
SimpleCSharpConsoleApp dialog, select Class, and name it Car.cs, as shown in Figure 2-9.
39
Chapter 2 ■ Building C# Applications
Update the code to the following to create a Car class (you will learn all about classes over the next few
chapters):
namespace SimpleCSharpConsoleApp;
After saving the file, drag the Car.cs file from the Solution Explorer onto the Class Diagram. Once you
do this, you will find a visual representation of the class. If you click the arrow icon for a given type, you can
show or hide the type’s members. Underneath the Class Diagram is the Class Details window, which shows
the specifics of the selected class diagram (see Figure 2-10).
40
Chapter 2 ■ Building C# Applications
■■Note Using the Class Designer toolbar, you can fine-tune the display options of the designer surface.
The Class Details window not only shows you the details of the currently selected item in the diagram
but also allows you to modify existing members and insert new members on the fly.
The Class Designer Toolbox allows you to insert new types (and create relationships between these
types) into your project visually (see Figure 2-11). (Be aware you must have a class diagram as the active
window to view this toolbox.) As you do so, the IDE automatically creates new C# type definitions in the
background.
41
Chapter 2 ■ Building C# Applications
By way of example, drag a new class from the Class Designer Toolbox onto your Class Designer. Name
this class Make with public access and select Create new file. This will result in the creation of a new C# file
named Make.cs that is automatically added to your project. Now, using the Class Details window, add a
public string property named Name (see Figure 2-12).
42
Chapter 2 ■ Building C# Applications
If you now look at the C# definition of the Make class, you will see it has been updated accordingly:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SimpleCSharpConsoleApp
{
public class Make
{
public int Name
{
get => default;
set { }
}
}
}
■■Note Don’t worry about the extra using statements or the syntax of property. This will all be covered in
subsequent chapters.
Now, activate the designer file once again and drag another new class onto the designer and name
it SportsCar. Click the Inheritance icon in the Class Designer Toolbox and click the top of the SportsCar
icon. Next, click the mouse on top of the Car class icon. If you performed these steps correctly, you have just
derived the SportsCar class from Car (see Figure 2-13).
43
Chapter 2 ■ Building C# Applications
To complete this example, update the generated SportsCar class with a public method named
GetPetName(), authored as follows:
As you would expect, the designer shows the added method to the SportsCar class.
This concludes your first look at Visual Studio. Now let’s look at the most recent addition to the Visual
Studio family, Visual Studio Code.
https://code.visualstudio.com/download
After installing VS Code, you will want to add the C# extension found here:
https://marketplace.visualstudio.com/items?itemName=ms-dotnettools.csharp
■■Note Visual Studio Code is used to develop many different types of applications based on a multitude of
languages. There are extensions for Angular, View, PHP, Java, and many, many, more.
44
Chapter 2 ■ Building C# Applications
This creates a new solution file with the name (-n) SimpleCSharpConsoleApp in a subdirectory (of the
current directory) named VisualStudioCode. When using Visual Studio Code with a single project app, there
is no need to create a solution file. Visual Studio is solution centric; Visual Studio Code is code centric. We
created a solution file here to duplicate the process in the Visual Studio example.
■■Note These examples use the Windows directory separators. Adjust the separators based on your
operating system.
Next, create a new C# 9/.NET 5 (-f net6.0) console application named (-n) SimpleCSharpConsoleApp
in a subdirectory (-o) of the same name (note that this command must be all on one line):
Finally, add the newly created project to the solution with the following command:
■■Note This is just a small sample of what the CLI is capable of. To discover everything the CLI can do, enter
dotnet -h.
45
Chapter 2 ■ Building C# Applications
The code editor (5) is complete with color coding and IntelliSense support. The code map (6) shows the
map of your entire code file, and the Problems/Output/Debug Console/Terminal window (7) receives the
output from debug sessions and accepts input from the user.
dotnet restore
To restore and build all of the projects in your solution, execute the following in the terminal/command
window (again, making sure the command is executed in the same directory as the solution file):
dotnet build
46
Chapter 2 ■ Building C# Applications
■■Note When dotnet restore and dotnet build are executed in a directory that contains a solution
file, all of the projects in the solution are acted on. The commands can also be run on a single project by
running the command in the directory of the C# project file (*.csproj).
To run your project without debugging, execute the following .NET CLI command in the same directory
as the project file (SimpleCSharpConsoleApp.csproj):
dotnet run
https://docs.microsoft.com/en-us/dotnet/csharp/
47