Vaskaran Sarcar

Simple and Efficient Programming with C#

Skills to Build Applications with Visual Studio and .NET

2nd ed.
Vaskaran Sarcar
Kolkata, West Bengal, India
ISBN 978-1-4842-8736-1e-ISBN 978-1-4842-8737-8
© Vaskaran Sarcar 2021, 2023
This work is subject to copyright. All rights are solely and exclusively licensed by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.
The publisher, the authors, and the editors are safe to assume that the advice and information in this book are believed to be true and accurate at the date of publication. Neither the publisher nor the authors or the editors give a warranty, expressed or implied, with respect to the material contained herein or for any errors or omissions that may have been made. The publisher remains neutral with regard to jurisdictional claims in published maps and institutional affiliations.

This Apress imprint is published by the registered company APress Media, LLC, part of Springer Nature.

The registered company address is: 1 New York Plaza, New York, NY 10004, U.S.A.

I dedicate this book to the programming lovers of C#.

Introduction

It is my absolute pleasure to write the second edition of Simple and Efficient Programming with C#: Skills to Build Applications with Visual Studio and .NET. You can surely guess that I got this opportunity because you liked the previous edition of the book and shared your feedback with us. So, once again I’m excited to join you and help you to learn more. This time I present a further simplified, better organized, and more content-rich edition to you.

Let me remind you of the key goals of this book. I wrote about them in the first edition as well. C# is an object-oriented programming (OOP) language. You may already know C# keywords or even some interesting features. You may also know how to write simple programs in C#. You can learn these things from an introductory book or an online tutorial. These are useful things to know, but they are not sufficient to understand an enterprise codebase. This is why a novice programmer often finds it difficult to understand an expert’s code. They may wonder why an experienced programmer wrote the program in a particular way. It may appear to the novice that the expert could have used an easier approach to solve the problem. But there are reasons why an experienced programmer might follow a different approach. The word experienced indicates that these programmers have more experience in programming and know the pros and cons of different approaches. They know how the C# features can be used in the best possible way to develop an application. So, the applications they make are usually powerful. What do I mean by a powerful application? For me, a powerful application is robust, extensible, and easily maintainable, but simple to use. This book is an introductory guide for developing such applications. This was the core aim of this book.

To write better-quality programs, senior programmers follow experts’ footprints. They learn from the collective wisdom and recorded experience of the past. So, instead of attempting an entirely new solution, you should first consider this knowledge base, which will help you produce better-quality code. It is always better if you know about why you should or shouldn’t follow any specific guideline.

Malcolm Gladwell, in his book Outliers (Little, Brown and Company), discussed the 10,000-hour rule. This rule says that the key to achieving world-class expertise in any skill is, to a large extent, a matter of practicing the correct way, for a total of around 10,000 hours. I acknowledge that it is impossible to consider all experiences before you write a program. Also, sometimes it is OK to bend the rules if the return on investment (ROI) is nice. So, keep in mind the Pareto principle, or the 80-20 rule. This rule simply states that 80 percent of outcomes come from 20 percent of all causes. This is useful in programming too. When you identify the most essential characteristics of top-quality programs and use them in your applications, you also qualify yourself as an experienced programmer, and your application will be robust, flexible, and maintainable. In this book, I share with you these important principles using some case studies, which will help you write better programs. Some of these principles you may know already, but when you see them in action and compare these case studies, you’ll understand their importance.

So, what is new in this second edition? Well, the first thing I want to tell you is that this edition maintains the same goals that were mentioned in the first edition. Second, you can easily guess that it is a further simplified, enlarged, and polished version. This time you see the use of top-level statements throughout the book. You may know that top-level statements have been supported since C# 9.0. In addition, the .NET 6+ project template for C# console apps uses top-level statements. At the time of this writing, C# 11 is not released, but you can test the preview features. I have taken this opportunity to use some of them, particularly raw-string literals. I talk about static abstract interface members too. I used many preview features in my other book, Test Your Skills in C# Programming. But for this book, not all of them are required.

Additionally, this is an expanded edition. Two new chapters in Part IV, Chapter 10 and Chapter 11, talk about handling errors in a better way. Particularly, you’ll see a discussion of organizing exceptions and handling null values with different case studies.

How Is the Book Organized?

The book has five major parts, which are as follows:
  • The first three chapters form Part I, in which there is a detailed discussion of polymorphism and the use of abstract classes and interfaces. Here, code comments will be examined, and you will learn when to use them effectively. These are the fundamental building blocks for the rest of the book.

  • In the world of programming, there is no shortage of programming principles and design guidelines. Each of these suggestions has its own benefits. To become a professional programmer, you do not need to learn everything at the same time. In Part II, I discuss six design principles, which include the SOLID principles and the DRY principle. These are the foundation of well-known design patterns.

  • The best way to learn is by doing and analyzing case studies. So, in Part III of the book, you will see interesting applications that use some well-known patterns. This part gives you hints about how a professional coder develops an enterprise application.

  • Handling errors is an unavoidable part of programming. Particularly, runtime exceptions are dangerous, and often they appear in the form of NullReferenceException in C#. Part IV focuses on them, discusses different case studies with easy-to-understand examples, and provides useful suggestions about possible improvements.

  • There is no end to learning. So, Part V includes some interesting topics such as how to prevent memory leaks, how to choose between a static method and an instance method, and some common terms from software development that are not discussed in detail in this book. A quick overview of these topics will help your future learnings and experiments.

  • You can download all the source codes for the book from the publisher’s website. I have a plan to maintain the “errata,” and, if required, I can also make some updates/announcements there. So, I suggest you visit those pages to receive any important corrections or updates.

Prerequisite Knowledge

This book is intended for those who are familiar with the common language constructs of C# and have a basic understanding of pure object-oriented concepts such as polymorphism, inheritance, abstraction, encapsulation, and, most importantly, how to compile or run a C# application in Visual Studio. This book does not invest time in easily available topics, such as how to install Visual Studio on your system, how to write a “Hello World” program in C#, how you can use an if-else statement or a while loop, etc. This book is written using the most basic features of C# so that for most of the programs herein you do not need to be familiar with advanced topics in C#. The examples are simple, and I believe that they are written in such a way that even if you are familiar with another popular language such as Java, C++, and so on, you can still easily grasp the concepts in this book.

Who Is This Book For?

In short, you can pick up this book if the answer is “yes” to the following questions:
  • Are you familiar with basic constructs in C# and object-oriented concepts such as polymorphism, inheritance, abstraction, and encapsulation?

  • Do you know how to set up your coding environment?

  • Have you completed at least one introductory course on C# and now are interested in writing better programs?

  • Are you also interested to know how a professional programmer designs their applications?

You probably shouldn’t pick this book if the answer is yes to any of the following questions:
  • Are you absolutely new to C#?

  • Are you looking for advanced concepts in C#, excluding the topics mentioned previously?

  • Are you interested in exploring a book where the focus is not on standard design principles?

  • Do you not like Windows, Visual Studio, and/or .NET and want to learn and use C# without them?

Guidelines for Using This Book

To use this book more effectively, consider the following:

  • This book works best if you’ve gone through an introductory course on C# and are familiar with the common terms, such as polymorphism, and have heard about abstract classes and interfaces. If this is not the case, please read about these topics before you start reading this book.

  • I suggest you go through the chapters sequentially. This is because some fundamental design techniques may have been discussed in a previous chapter, and I have not repeated those techniques in later chapters.

  • I started this book using Microsoft Visual Studio Community 2022 in a Windows 10 environment. This community edition is free of charge. When I started the book, I started with the latest versions of C# that were available at that time. You can easily guess that version updates kept coming, so I kept updating my code repository. When I finished my first draft, I had the most recent version of Visual Studio Community 2022 (version 17.3.3). Almost in every case, my target framework was .NET 7.0, which supports C# 11.

  • In this context, it is useful to know that nowadays the C# language version is automatically selected based on your project’s target framework(s), so you can always get the highest compatible version by default.

  • For example, C# 11 is for .NET 7 and later versions. Similarly, C# 10 is supported only on .NET 6 and newer versions. C# 9 is supported only on .NET 5 and newer versions. C# 8.0 is supported only on .NET Core 3.x and newer versions. If you are interested in the C# language versioning, you can go to this link: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/configure-language-version.

  • The fact is that these version updates will come continuously, but I strongly believe that these version details should not matter much to you because I have used the fundamental constructs of C#. So, the code in this book should execute smoothly in the upcoming versions of C#/Visual Studio as well. Though I also believe that the results should not vary in other environments, you know the nature of software—it is naughty. So, I recommend that if you want to see the exact same output, you mimic the same environment.

  • If you do not use the Windows operating system, you can use Visual Studio Code, which is also a source-code editor developed by Microsoft to support Windows, Linux, or Mac operating systems. This multiplatform IDE is also free.

  • You can download and install the Visual Studio IDE from https://visualstudio.microsoft.com/downloads/. You will the screen shown in Figure I-1.

    Note At the time of writing, this information is correct. But the link and policies may change in the future.

  • I have also installed the class designer component in Visual Studio 2022 to draw class diagrams for my programs. They’ll help you understand the code better.

Figure I-1

Download link for Visual Studio 2022 and Visual Studio Code

Conventions Used in This Book

All the output and code of the book follow the same font and structure. To draw your attention to some places, I have made them bold. For example, consider the following code fragment and the lines in bold (taken from Chapter 4 when I discuss the LSP):
// The previous codes are skipped
// Instantiating two registered users
RegisteredUser robin = new("Robin");
RegisteredUser jack = new("Jack");
helper.AddUser(robin);
helper.AddUser(jack);
GuestUser guestUser1 = new();
helper.AddUser(guestUser1);
// Processing the payments using
// the helper class.
// You can see the problem now.
helper.ShowPreviousPayments();
helper.ProcessNewPayments();
// The remaining codes are skipped

Final Words

You are an intelligent person. You have chosen a subject that can assist you throughout your career. As you learn about these concepts, I suggest you write your own code; only then will you master this area. There is no shortcut to true learning. In a similar context, can you remember Euclid’s (the ancient Greek mathematician who is often considered the father of geometry) reply to the ruler? If not, let me remind you of his reply: “There is no royal road to geometry.” Similarly, in programming, there is no shortcut. So, study and code; understand a new concept and code again. Do not give up when you face challenges. They are the indicators that you are growing better.

I believe that this book is designed for you in such a way that upon its completion, you will develop an adequate knowledge of the topic, and, most importantly, you’ll know how to go further. Lastly, I hope that this book can provide help to you and that you will value the effort.

Table of Contents
About the Author
Vaskaran Sarcar
obtained his master’s degree in software engineering from Jadavpur University, Kolkata (India), and his MCA from Vidyasagar University, Midnapore (India). He was a National Gate Scholar (2007–2009) and has more than 12 years of experience in education and the IT industry. Vaskaran devoted his early career (2005–2007) to the teaching profession at various engineering colleges, and later he joined HP India PPS R&D Hub Bangalore. He worked there until August 2019. At the time of his retirement from HP, he was a senior software engineer and team lead. To follow his dream and passion, Vaskaran is now an independent full-time author. Other Apress books by Vaskaran include:
  • Test your Skills in C# Programming (Apress, 2022)

  • Java Design Patterns, Third Edition (Apress, 2022)

  • Simple and Efficient Programming in C# (Apress, 2021)

  • Design Patterns in C#, Second Edition (Apress, 2020)

  • Getting Started with Advanced C# (Apress, 2020)

  • Interactive Object-Oriented Programming in Java, Second Edition (Apress, 2019)

  • Java Design Patterns, Second Edition (Apress, 2019)

  • Design Patterns in C# (Apress, 2018)

  • Interactive C# (Apress, 2017)

  • Interactive Object-Oriented Programming in Java (Apress, 2016)

  • Java Design Patterns (Apress, 2016)

The following are other books he’s written:
  • Python Bookcamp (Amazon, 2021)

  • Operating System: Computer Science Interview Series (Createspace, 2014)

 
About the Technical Reviewers
Shekhar Kumar Maravi
is a lead engineer in design and development whose main interests are programming languages, algorithms, and data structures. He obtained his master’s degree in computer science and engineering from the Indian Institute of Technology – Bombay. After graduation, he joined Hewlett-Packard’s R&D Hub in India to work on printer firmware. Currently he is a technical lead engineer for automated pathology lab diagnostic devices at Siemens Healthcare R&D division. He can be reached by email at [email protected] or via LinkedIn at www.linkedin.com/in/shekharmaravi.
 
Carsten Thomsen
is a back-end developer primarily but works with smaller front-end bits as well. He has authored and reviewed a number of books and created numerous Microsoft Learning courses, all to do with software development. He works as a freelancer/contractor in various countries in Europe, using Azure, Visual Studio, Azure DevOps, and GitHub. He also enjoys working with architecture, research, analysis, development, testing, and bug fixing.
 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.193.7