1. Hello C#
Overview
This chapter introduces you to the basics of C#. You will start by learning about the basics of the .NET Command-Line Interface (CLI) and how to use Visual Studio Code (VS Code) as a basic Integrated Development Environment (IDE). You will then learn about the various C# data types and how to declare variables for these types, before moving on to a section about arithmetic and logical operators. By the end of the chapter, you will know how to handle exceptions and errors and be able to write simple programs in C#.
Introduction
C# is a programming language created in the early 2000s by a team at Microsoft led by Anders Hejlsberg, who is also among the creators of some other popular languages, such as Delphi and Turbo Pascal, both widely used in the 1990s. Over the last 20 years, C# has grown and evolved, and today it is one of the most widely used programming languages globally, according to Stack Overflow's 2020 insights.
It has its reasons for holding such an honorable place in the tech community. C# allows you to write applications for a wide segment of markets and devices. From the banking industry, with its high-security standards, to e-commerce companies, which hold enormous volumes of transactions, it is a language trusted by companies that need both performance and reliability. Besides that, C# also makes it possible to write web, desktop, mobile, and even IoT applications, allowing you to develop for almost every kind of device.
C# was initially limited to work only on Windows...
Running and Developing C# with the .NET CLI
One term you'll hear a lot in the C# world is .NET. It is the foundation of C#, a framework that the language is built on top of. It has both a Software Development Kit (SDK) that allows the language to be developed and a runtime that allows the language to run.
That said, to start developing with C#, you only need to install the .NET SDK. This installation will provide both a compiler and the runtime on the development environment. In this section, you will cover the basic steps of preparing your environment for developing and running C# locally.
Note
Please refer to the Preface of this book for step-by-step instructions on how to download the .NET 6.0 SDK and install it on your machine.
Once the installation of the .NET 6.0 SDK is completed, you will have something called the .NET CLI. This Command-Line Interface (CLI) allows you to create new projects, compile them, and run them with very simple commands that you can run...
Data Types
In this section, you will talk about the main data types within C# and their functionalities.
Strings
C# uses the string
keyword to identify data that stores text as a sequence of characters. You can declare a string in several ways, as shown in the following snippet. However, when assigning some value to a string variable, you must place the content between a pair of double quotes, as you can see in the last two examples:
// Declare without initializing. string message1; // Initialize to null. string message2 = null; // Initialize as an empty string string message3 = System.String.Empty; // Will have the same content as the above one string message4 = ""; // With implicit declaration var message4 = "A random message" ;
One simple but effective technique (that you used in the preceding Exercise 1.02) is one called string interpolation. With this technique, it is very simple to mix plain text values with variable values, so that the...
Classes
Classes are an integral part of coding in C# and will be covered comprehensively in Chapter 2, Building Quality Object-Oriented Code. This section touches upon the basics of classes so that you can begin using them in your programs.
The reserved class
keyword within C# is used when you want to define the type of an object. An object, which can also be called an instance, is nothing more than a block of memory that has been allocated to store information. Given this definition, what a class does is act as a blueprint for an object by having some properties to describe this object and specifying the actions that this object can perform through methods.
For example, consider that you have a class named Person
, with two properties, Name
and Age
, and a method that checks whether Person
is a child. Methods are where logic can be placed to perform some action. They can return a value of a certain type or have the special void
keyword, which indicates that they do not return...
Dates
A date can be represented in C# using the DateTime
value type. It is a struct with two static properties called MinValue
, which is January 1, 0001 00:00:00, and MaxValue
, which is December 31, 9999 11:59:59 P.M. As the names suggest, both these values represent the minimum and maximum dates according to the Gregorian calendar date format. The default value for DateTime
objects is MinValue
.
It is possible to construct a DateTime
variable in various ways. Some of the most common ways are as follows:
- Assigning the current time as follows:
var now = DateTime.Now;
This sets the variable to the current date and time on the calling computer, expressed as the local time.
var now = DateTime.UtcNow;
This sets the variable to the current date and time on this computer, expressed as the Coordinated Universal Time (UTC).
- You can also use constructors for passing days, months, years, hours, minutes, and even seconds and milliseconds.
- There is also a special...
Logical Operators and Boolean Expressions
You are already familiar with these. Recall that in the preceding exercise, you did the following comparison:
var now = DateTime.Now.Date == DateTime.UtcNow.Date;
This output assigns the value true
to now
if the dates are equal. But as you know, they might not necessarily be the same. Therefore, if the dates are different, a false
value will be assigned. These two values are the result of such Boolean expressions and are called Boolean values. That is why the now
variable has the type of bool
.
Boolean expressions are the base for every logical comparison in every program. Based on these comparisons, a computer can execute a certain behavior in a program. Here are some other examples of Boolean expressions and variable assignments:
- Assigning the result of a comparison that checks whether
a
is greater thanb
:var basicComparison = a > b;
- Assigning the result of a comparison that checks whether
b
is greater than or...
Summary
This chapter gave you an overview of the fundamentals of C# and what it looks like to write programs with it. You explored everything from the variable declaration, data types, and basic arithmetic and logical operators to file and exception handling. You also explored how C# allocates memory while dealing with value and reference types.
In the exercises and activities in this chapter, you were able to solve some real-world problems and think of solutions that can be implemented with this language and its resources. You learned how to prompt for user inputs in console apps, how to handle files within a system, and finally, how to deal with unexpected inputs through exception handling.
The next chapter will cover the essentials of Object-oriented programming, diving deeper into the concept of classes and objects. You will also learn about the importance of writing clean, concise code that is easy to maintain, and the principles you can follow for writing such code...