Home Programming The C# Workshop

The C# Workshop

By Jason Hales , Almantas Karpavicius , Mateus Viegas
books-svg-icon Book
eBook $41.99 $28.99
Print $51.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $41.99 $28.99
Print $51.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    2. Building Quality Object-Oriented Code
About this book
C# is a powerful, versatile language that can unlock a variety of career paths. But, as with any programming language, learning C# can be a challenging process. With a wide range of different resources available, it’s difficult to know where to start. That's where The C# Workshop comes in. Written and reviewed by industry experts, it provides a fast-paced, supportive learning experience that will quickly get you writing C# code and building applications. Unlike other software development books that focus on dry, technical explanations of the underlying theory, this Workshop cuts through the noise and uses engaging examples to help you understand how each concept is applied in the real world. As you work through the book, you'll tackle realistic exercises that simulate the type of problems that software developers work on every day. These mini-projects include building a random-number guessing game, using the publisher-subscriber model to design a web file downloader, creating a to-do list using Razor Pages, generating images from the Fibonacci sequence using async/await tasks, and developing a temperature unit conversion app which you will then deploy to a production server. By the end of this book, you'll have the knowledge, skills, and confidence to advance your career and tackle your own ambitious projects with C#.
Publication date:
September 2022
Publisher
Packt
Pages
780
ISBN
9781800566491

 

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 than b:
    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...

About the Authors
  • Jason Hales

    Jason Hales has been developing low-latency, real-time applications using various Microsoft technologies since the first release of C# in 2001. He is a keen advocate of design patterns, OO principles, and test-driven practices. When he's not dabbling with code, he likes to spend time with his wife, Ann, and their three daughters in Cambridgeshire, UK.

    Browse publications by this author
  • Almantas Karpavicius

    Almantas Karpavicius is a lead software engineer working in the information and technology company, TransUnion. He has been a professional programmer for over five years. On top of his full-time programming career, Almantas has spent three years teaching programming for free in his free time on Twitch. He is a founder of a C# programming community called C# Inn that boasts over 7000 members and the creator of two free C# boot camps in which he has helped hundreds of people get a start in their careers. He has taken interviews with programming celebrities, such as Jon Skeet, Robert C. Martin (Uncle Bob), Mark Seemann, and was also a part-time Java teacher for a time. Almantas likes talking about software design, clean code, and architecture. He is also interested in Agile (Scrum, in particular) and is a big fan of automated tests, especially those done using BDD. He also holds a two-year Microsoft MVP.

    Browse publications by this author
  • Mateus Viegas

    Mateus Viegas has been working in Software Engineering and Architecture for over a decade, dedicating the last few years to Leadership and Management roles. His main interests in technology are C#, Distributed Systems, and Product Development. A lover of the outdoors, when not working he likes to spend his time either exploring nature with his family, taking photographs, or running.

    Browse publications by this author
The C# Workshop
Unlock this book and the full library FREE for 7 days
Start now