Full download Code Like a Pro in C MEAP V05 Jort Rodenburg pdf docx
Full download Code Like a Pro in C MEAP V05 Jort Rodenburg pdf docx
Full download Code Like a Pro in C MEAP V05 Jort Rodenburg pdf docx
com
https://textbookfull.com/product/code-like-a-pro-in-c-
meap-v05-jort-rodenburg/
OR CLICK BUTTON
DOWNLOAD NOW
https://textbookfull.com/product/code-like-a-pro-in-rust-1st-edition-
brenden-matthews/
textboxfull.com
https://textbookfull.com/product/kubernetes-in-action-second-edition-
meap-v05-marko-luksa/
textboxfull.com
https://textbookfull.com/product/get-programming-with-scala-
meap-v05-daniela-sfregola/
textboxfull.com
https://textbookfull.com/product/get-programming-with-scala-
meap-v05-daniela-sfregola-2/
textboxfull.com
Testing JavaScript Applications MEAP V05 Lucas Da Costa
https://textbookfull.com/product/testing-javascript-applications-
meap-v05-lucas-da-costa/
textboxfull.com
https://textbookfull.com/product/five-lines-of-code-
meap-v04-christian-clausen/
textboxfull.com
https://textbookfull.com/product/how-to-build-a-sauna-building-your-
own-cheap-indoor-sauna-from-scratch-like-a-pro-victor-allan/
textboxfull.com
https://textbookfull.com/product/functional-programming-in-c-how-to-
write-better-c-code-1st-edition-enrico-buonanno/
textboxfull.com
Thank you for purchasing the MEAP for Code Like a Pro in C#. I wrote this book for people with
previous experience in object-oriented programming to teach them the ways of writing
amazing C# code. It doesn’t matter whether your experience is in C#, Java, Kotlin, or any
other language. With this book’s focus on how to write clean, readable, idiomatic C# code, you
won’t find granular descriptions of what a for-loop or a variable is. Instead, you’ll find practical
techniques and concepts that can elevate your code and impress your peers.
The first time I encountered C# and .NET was when I was hired by a Microsoft shop.
Previously, I worked in Java, a language I found simultaneously easy to understand yet wonky
in some of its design decisions. (There were also bleak periods of work in Python and Delphi,
but I don’t publicly admit to that.) To hit the ground running at my new job, I had to get up to
speed quickly, so I couldn’t afford to start with a book along the lines of “Learn Programming
through C#” or “Programming 101.” At the end of day one, I was versed in the syntax of C#
and could cobble together some unit tests against the existing codebase. Two weeks later, I
had forced my way through some beginner and advanced resources, not knowing how to fill my
knowledge gaps or sometimes not even aware that I had them. If I had had this book when I
was switching to C#, my journey would have been a lot easier.
Throughout this book, you follow a fictitious airline in its struggle to update their codebase.
You learn how to rewrite legacy code and how to make it conform to clean code principles and
security concepts, and how to make readability improvements. I hope this book can serve you
in your development journey. If you have been writing C# for many years and want to elevate
your skill level: welcome. If you were told by your manager that you need to “pick up C# by
the afternoon”: also welcome and I’m sorry.
In closing, I ask you to do me one favor. It’s a small one, I promise. If you find something
that is exceptionally boring, not explained very well, or simply wrong: please let me know in
the book’s forum.
Thank you,
Jort Rodenburg
Part One
In this first part of the book, we take a brief tour of the C# language and talk about some of
its unique features. Chapter 1 covers what C# and .NET are and why you would (and would
not) use them for your projects. Chapter 2 looks at some of the features that the .NET
Framework offers us that are not always present in other platforms. We also take a C#
method based on the Pythagorean Theorem through C#’s compilation process, stopping at
each major step along the way.
This part is truly the introduction of this book but it still provides invaluable information
to somebody familiar with C#. Some of the knowledge introduced in these first two chapters
are things you need to know before moving onto more advanced resources.
and a mug of hot chocolate on a winter day, providing you with everything you need. Filled
with libraries that encapsulate low-level Windows APIs, expose commonly used data
structures, and wrappers for complicated algorithms. Since daily development in C# almost
certainly involves the .NET Framework or .NET Core, we explore these frameworks where
appropriate.
For those of you with prior experience in C#: this book sits between beginner and
advanced resources. With this book in hand, you can bridge the knowledge gap and prepare
yourself for advanced concepts. The first two chapters may seem a bit basic to you. I invite
you to not skim over these. It is always good to refresh your knowledge.
Figure 1.1 C# supports scalable software development due to its multiplatform capabilities. C# is open-source,
and therefore free to use. The language contains mature native libraries that help with secure coding and
promotes self-documenting code. This helps us in writing maintainable code. There is also a massive online
community around the language and fantastic documentation provided by Microsoft. This helps a developer
get up to speed quickly with the language.
So why C#, then? Well, I promise not to repeatedly tell you that C# is a “strongly typed
object-oriented programming language that enables cross-platform development of scalable
enterprise software.” You are likely already aware of that, and it is hardly the most exciting
sentence to dissect. In this section, we cover the buzzwords in that definition once and do
not touch on it again. At the risk of sounding like I’m employed by Microsoft’s marketing
department, for the rest of this section we focus on some highlights and use cases of C#:
2. C# can improve code stability and is maintainable because of its support for self-
documenting code, secure libraries, and ease of use.
3. C# is developer-friendly and easy to use. There’s nothing worse than discovering that
the programming language you want to use does not have good support for the things
you love (such as a stable package manager, testing libraries for Test-Driven-
Development, and a cross-platform runtime).
Of course, writing scalable, maintainable, and developer-friendly “clean code can be done in
most (if not all) programming languages. The difference lies in the developer experience.
Some languages are really good at guiding you in writing clean code while others are not. C#
is not perfect, but it does try and help you in this regard.
DEFINITION Self-documenting code means code that is written clearly enough that we need no comments
to explain the logic. The code documents itself. For example, if you have a method called
DownloadDocument we have some inkling of what the DownloadDocument method does. There is no
need to add a comment saying that the logic inside the method downloads a document.
To top things off, perhaps we can have some good integration with some cloud service for
continuous integration and delivery (CI/CD)? A pragmatic view tells us that the likelihood of
you having such a codebase is not very high. Of course, this is an unrealistic wish list for
most scenarios. However, if you wanted to do some of these things (or all of them, if you are
adventurous), C# does not work against you. There are existing workflows, functionalities,
and native libraries to get you 99 percent of the way there.
Developers coming from a language such as Java should see some familiarity in the
project structure. While there are some differences, they are not large. We discuss C#
project structure in depth throughout the book. Another important difference between Java
and C# highlighted in the book are streams. They mean very different things depending on
whether you work in Java or C#.
.NET also has support for several popular testing frameworks. Microsoft provides the
“Visual Studio Unit Testing Framework” which contains (and by extension is sometimes
called) “MSTest”. MSTest is just the command line runner for the Visual Studio Unit Testing
Framework. Other commonly testing frameworks are “xUnit” and “nUnit”. There is also
support for Moq (Moq is very similar to Java’s Mockito or Go’s gomock. We learn more about
using Moq with unit tests in section 10.3.3), SpecFlow (behavior-driven development similar
to Cucumber), NFluent (a fluent assertion library), FitNesse, and many more.
Lastly, you can run C# on a host of platforms, albeit with some limitations (some older
platforms are restricted to older versions of C# and the .NET Framework). With .NET Core,
you can run the same code on Windows 10, Linux, and macOS. .NET Code started as a
spinoff of the .NET Framework, but is now merging with .NET Framework (and other
frameworks) to create .NET 5. There are even ways to run C# code on iOS and Android
through Xamarin, and on PlayStation, Xbox, and Nintendo Switch platforms through Mono.
Let’s examine briefly why C# might not be an ideal fit for these use cases.
1 The name “Mesa” is a pun referring to the programming language being “high-level”, just like the isolated elevated hill with a flat top.
1.3 Switching to C#
Because of the similarity between languages, developers with a good understanding of a JVM
language (most notably Java, Scala, and Kotlin) or C++ may have an easier time with this
book than somebody coming from a non-C style language, non-virtual-machine-esque-based
language, or web languages such as Dart, Ruby, or Go (although Go could also be construed
as a “cloud” language). Coming from a non-C style language background does not mean that
C# is impossible to understand. You may find yourself rereading some passages twice, but in
the end, you’ll get there just fine.
If you come from an interpreted language such as Python, the .NET compilation process
may seem odd at first. Languages within the confines of .NET use a “two-step” compilation
process. First, code is compiled statically to a lower-level language called Common
Intermediate Language (CIL, IL, or MSIL for short; MS for Microsoft. It is somewhat similar
to Java bytecode, for the Java developers among us), which in turn compiles “Just-In-Time”
(JIT) to native code when the .NET runtime executes the code on the host. All this might
sound like a lot to digest suddenly, but in a few chapters, you will understand all the above.
If you come from a scripting language such as JavaScript, static typing might seem to
limit and frustrate you. But once you get used to knowing what your type is at all times, I
think you’ll like it.
And if you come from a language such as Go or Dart, where native libraries are
sometimes hard to find: The .NET Framework and .NET Core may surprise you with its rich
store of libraries. By providing functions for most things you can think of, the .NET libraries
are your primary source for functionality. A lot of applications written with .NET never use
any third-party libraries.
To get the housekeeping out of the way, let’s discuss tooling. We do not dive into how to
install an IDE or the .NET SDK in this chapter. If you have not installed a .NET SDK or an
IDE and want some help, there are a couple of quick installation guides in Appendix C. To
follow along with this book, you need to install the latest versions of .NET Core and .NET
Framework (separately) until the release of .NET 5. With the release of .NET 5, .NET Core
and .NET Framework merge. We examine this merger in the next chapter.
As mentioned before, C# is open-source and maintained by the community with help
from Microsoft. You don’t need to pay for a runtime, SDK, or IDE license. Concerning IDEs,
Visual Studio (the IDE we use in the examples in this book) has a free “community” edition
that you can use to develop personal projects and open-source software. If you like your
current IDE, chances are you can find a C# plugin for it. You can also use the command line
to compile, run, and test C# projects, although I encourage you to give the dedicated C#
tooling (Visual Studio) a chance as it provides the smoothest experience and easiest route to
writing idiomatic C# code.
Many concepts and techniques you have picked up elsewhere transfer to C#, but some
don’t. C# has matured more on the backend than it has on the frontend, as it is traditionally
mostly used for that purpose. A historical focus on backend development for C# does not
mean that the frontend experience is any less impressive. You can write a full-stack
application in C# without the need to touch JavaScript. Although this book focuses on
backend development, many of the concepts taught in this book help you on the frontend as
well. To further help you get familiar with C# and .NET, this book contains exercises and two
full-length kata walkthroughs (chapters 15 and 16) that reinforce the topics discussed
throughout the book.
Imagine you are not the person who wrote the code, but a new developer that just joined
your team. How would you feel when you boot up your IDE, pull down the source code, and
see this method? Despair would not quite cover it. Now imagine that you placed all the
individual actions in your monster method in their own small methods (perhaps fewer than
five to ten lines of code). What would your monster method look like? Instead of being a
bunch of difficult-to-follow conditionals and assignments, with no clear path to understanding
unless you have specific domain knowledge, the code almost reads like a narrative. If you
name your methods well, your main method should read like a recipe that even the worst
cooks can follow.
When I refer to “clean code,” I refer to the coding practices evangelized by Robert C.
Martin in his videos (https://cleancoders.com/videos) and books Clean Code (Prentice Hall,
2008); Clean Architecture (Prentice Hall, 2017); and, with Micah Martin, Agile Principles,
Patterns, and Practices in C# (Pearson, 2006); and as well as through his compilation of the
“SOLID” principles (Single Responsibility Principle, Open/Closed Principle, Liskov Substitution
Principle, Interface Segregation Principle, and Dependency Inversion Principle). I explain
clean code principles fully when they come up in the book along with practical information on
how to actually use them.
At the end of the day, why bother writing clean code? Clean code works like a washing
machine for bugs and incorrect functionality. If we put our codebase in the Clean Code
washing machine, we see that once you refactor something to be more “clean,” bugs come
out and incorrect functionality stares at you with no place to hide. After all, “it all comes out
in the wash”.
Bugs
Code
Code
Clean Code Washing Machine
Figure 1.2 Clean Code is like a washing machine for your code. It takes your dirty laundry (your code), adds
soap and water (clean code principles), and separates the dirt from the clothes (separates the bugs from the
code). What it leaves you with are clothes (code) with less dirt (bugs) than you started with. Clean Code helps
you write code that contains fewer bugs.
This book contains sidebars with information on clean code topics. If the sidebars are clean-
code related, I denote them as such and explain both the concepts and how to apply them to
the real world. Appendix B contains a “Clean Code Checklist.” You can use the “Clean Code
Checklist” to determine whether you need to refactor the existing code. The checklist serves
as a reminder for some of the more forgettable (but still important) concepts.
So, what do you need to know to get the most out of this book? The expectation is that you
understand the basic principles of object-oriented programming (inheritance, encapsulation,
abstraction, and polymorphism) and are familiar with another programming language that
supports developing code through an Object-Oriented approach, even if not an intrinsic
feature of the language (be it C++, Go, Python, or Java).
After reading this book, you’ll write clean, secure, testable C# code that follows good
object-oriented design principles. Additionally, you’ll be ready to further deepen your
knowledge in C# through advanced resources. Some suggested readings for after this book
are Jon Skeet’s C# In-Depth, fourth edition (Manning, 2019), Jeffrey Richter’s CLR via C#.
fourth Edition (Microsoft Press, 2012), Bill Wagner’s Effective C#, second edition (Microsoft
Press, 2016), Dustin Metzgar’s .NET Core in Action (Manning, 2018), John Smith’s Entity
Framework Core in Action, second edition (Manning, 2021), and Andrew Lock’s ASP.NET Core
in Action, second edition (Manning, 2021).
If you are new to programming, I highly recommend going through a book such as Jennifer
Greene’s Head First C#, fourth edition (O’Reilly, 2020) or Harold Abelson, Gerald Jay
Sussman, and Julie Sussman’s Structure and Interpretation of Computer Programs, second
edition (The MIT Press, 1996) 2 before reading this book.
This book also doesn’t cover some more specialized ways to use C# as follows:
• Microservice architecture. This book does not go into depth on what microservices are
and how to use them. Microservice architecture is very much the trend and is useful
in many use cases, but is not related to C# or how you code like a pro. Three
wonderful resources to learn more about microservices are Chris Richardson’s
Microservices Patterns (Manning, 2018), Prabath Siriwardena and Nuwen Dias’
Microservices Security in Action (Manning, 2019), and Christian Horsdal
Gammelgaard’s Microservices in .NET Core (Manning, 2020).
• How to use C# with containerized environments such as Kubernetes and/or Docker.
While very practical and used in many enterprise development environments, knowing
how to use Kubernetes or Docker does not guarantee you can “code like a pro” in C#.
To learn more about these technologies, see Marko Lukša’s Kubernetes in Action.
second edition (Manning, 2020), Elton Stoneman’s Learn Docker in a Month of
Lunches (Manning, 2020), and Ashley Davis’ Bootstrapping Microservices with Docker,
Kubernetes, and Terraform (Manning, 2020).
• Concurrency with C# beyond multi-threading, basic parallelism (chapter 17), and
locks (chapter 6). We often find this topic in highly threaded and performance-critical
scenarios. Most developers don’t work with such code much. If you do find yourself in
that position, an excellent resource to learn more about concurrent programming in
C# is Joe Duffy’s Concurrent Programming on Windows (Addison-Wesley, 2008).
• The deep internal details of either the CLR or the .NET Framework themselves. While
interesting, knowing every little detail about the CLR or .NET Framework (.NET Core
included) is of little practical use for most developers. This book covers the CLR and
.NET Framework in some detail but stops where things get unpractical or unwieldy.
The "bible” for the CLR and .NET Framework is Jeffrey Richter’s CLR via C#, fourth
edition (Microsoft Press, 2012). Note that Richter’s book does not cover .NET Core (or
CoreCLR) as .NET Core was introduced in 2016.
There are two ways of reading this book: the recommended way is to read the entire book,
front to back and in order. If you are only interested in refactoring and best practices, you
can just read parts 3 through 6. That leaves part 7, which contains two coding kata
walkthroughs. These thematically tie into the rest of the book but do not form part of the
overall narrative. They cover some topics (parallelism, string concatenation performance in
memory, the Strategy design pattern) that any developer would not want to miss in their
toolbox.
1. “Using C# and .NET”: In chapter 1 we discussed what this book is, what it teaches,
and what it does not teach. Chapter 2 is a brief tour of the C# language and .NET
framework, focusing on what sets .NET apart from other platforms and the C#
compilation story.
2. “Inheriting Code”: In this part, I guide you through the exploration of a code base we
inherit. This part is a detailed walkthrough of the existing code base, with a discussion
on potential improvements and design flaws.
3. “Refactoring the database access layer”: Following part 2, we start to rewrite the
entire service. In part 3, we focus on creating a new .NET Core project and learn how
we can use Entity Framework Core to connect to a cloud (or local) database. Other
discussed topics include the Repository/Service pattern, virtual methods and
properties, and sealed classes.
4. “Refactoring the repository layer”: In part 4, we step into the lands of the
Repository/Service pattern and implement 5 repository classes. You also learn about
dependency injection, multithreading (including locking, mutexes, and semaphores),
custom equality comparisons, Test-Driven Development, generics, extension methods,
and LINQ.
5. “Refactoring the service layer”: The next step is to implement the service layer
classes. In part 5, we write 4 service layers from the ground up and talk about
reflection, mocking, coupling, runtime assertions and type checks, error handling,
structs, and yield return.
6. “Refactoring the controller layer”: Part 6 is the final step in our rewrite of the service
we initially inherited in part 2. This part sees us writing 2 controller classes, and has
us perform acceptance testing. Besides those topics, we also broach ASP.NET Core
middleware, HTTP routing, custom data binding, data serialization and deserialization,
and generating an OpenAPI specification a runtime.
7. “Coding Katas”: This part contains 2 full-length coding katas walkthroughs. The first
coding kata (chapter 15) revolves around the StringBuilder class, the Strategy design
pattern, and pausing threads. The second coding kata (chapter 16) discussed graph
theory, linked lists, and parallelism.
1. Start reading
Part 1
Part 4
6. Read chapters 10 - 12
Part 6
YES
Interesting only in... Part 3 4. Read chapter 5
NO
9. Done
Figure 1.3 A flowchart of suggested routes to read this book. Follow the steps and answer the questions to
achieve your ideal reading experience. This flowchart is inspired by the book structure flowcharts in Donald
Knuth’s The Art of Computer Programming series.
A lot of chapters in this book (and some sections within chapters) have exercises designed to
test your knowledge of the material. You can complete these exercises quickly. I encourage
you to complete these when you encounter them, and to revisit sections you may have
skimmed or misunderstood.
1.8 Summary
• This book doesn’t cover “Programming 101.” It assumes knowledge of object-oriented
programming. This allows us to focus on practical concepts.
• C# and .NET are free to use and open source, yet partially maintained (and originally
created) by Microsoft. This means that there is a lot of community support and we can
• The difference between .NET Core, .NET Framework, and other platforms
• The release of .NET 5
• The C# compilation process
• How to read Intermediate Language
Microsoft created the .NET Framework in the early 2000s. The original use-case for the .NET
Framework was developing enterprise Windows applications. The .NET Framework ties
together with a large collection of libraries. Whilst the .NET Framework and C# are often tied
at the hip, there are use cases for the .NET Framework without C# (we talk about some of
these when discussing the .NET Standard later on in this chapter). The two most important
pillars of what makes up the .NET Framework are the Framework Class Library (FCL; a
humongous class library that is the backbone of the .NET Framework) and the Common
Language Runtime (CLR; the runtime environment of .NET). In other words, The FCL
contains all the libraries you are likely to use and the CLR executes the code.
In this chapter, we discuss a couple of features of the .NET framework and contrast them
against implementations (and sometimes the lack thereof) in other platforms such as Java,
Python, and Go. After that, we learn about the C# compilation process by following a method
from C# to Common Intermediate Language to native code. These fundamental building
blocks allow us to have a solid foundation in our knowledge of the C# and .NET ecosystem. If
you are already very familiar with C# and .NET, this chapter is bound to have some
repetition for you. If nothing else, I suggest you read through section 2.4. The discussion on
the C# compilation process is deeper than what you find in most resources, and is assumed
knowledge in some advanced C# resources. To test your knowledge of the respective topics,
each section has exercises for you to try.
Table 2.1 Comparison of .NET Framework functionality versus other platforms (native/built-in
support only)
I chose the platforms in table 2.1 because of their widespread use and diversity in targeted
use cases (back-end, front-end, or full-stack). Developers use many other languages (think
about PHP, Groovy, Objective-C, Perl, Pascal, COBOL. The list goes on), but we have to draw
a line somewhere (even if it is an arbitrary one).
Because tuples are immutable, they are great at representing a database record. You can
mix and match types within a tuple, as long as the declaration matches the assignment. This
means that you can make your tuples as lengthy and complicated as you want, as long as
you assign the tuple to a set of objects with the same types (and order of types) as your
tuple variable. Listing 2.1 has examples of both a valid assignment where the variable and
assigned set have the same types (and order) and one where it does not.
#A These compile
#B This does not compile. Notice the type error in the second argument: float versus string.
When attempting to compile the invalid tuple in listing 2.1, we run into a compiler exception
(as shown in figure 2.1). The exception tells us it cannot automatically convert between a
string type and a float type. We told the compiler we are expecting a (string, float) yet
are assigning (string, string).
Figure 2.1 The code in listing 2.1 threw an exception telling us we cannot implicitly convert between strings
and floating-point types. CS0029 is the error code for this error.
Besides mixing types, you can also “deconstruct” tuples and use them as “named tuples”
(listing 2.2).
companyName = "Kodak";
isBankrupt = true;
Table 2.2 tells us that support for Tuples is not widespread amongst programming languages
with the most notable exceptions being Java and Go.
NOTE You can pronounce “tuple” in two ways. I prefer ‘tjʊpəl (rhymes with “scruple”) but some people say
ˈtʌpəl (rhymes with “couple”).
Java also supports events, but less explicitly than C#. Whereas C# knows the event
keyword, Java does not have any special syntax for events. JavaScript, on the other hand,
knows a thing or two about events and has very good support for them.
Looking at table 2.4, we can quickly see that a fair number of platforms support SQL out-of-
the-box to some extent. It also comes as no surprise that JavaScript and Ruby do not
provide libraries to query SQL databases, as web platforms should not connect to databases
directly (mainly for security reasons).
The .NET Framework has two main ways of connecting to SQL databases:
• using the built-in SqlConnection classes
• using Entity Framework (or Entity Framework Core for .NET Core).
It is up to you which one you want to use. Entity Framework Core is an open-source Object-
Relational Mapping (ORM) package maintained by Microsoft and the community that is
deeply ingrained in .NET. It is the easiest way of connecting to a database and it has drivers
for most database flavors. On the other hand, the built-in .NET Framework libraries offer a
stable, non-abstracted way of querying a database and retrieving information.
In this book, we use Entity Framework Core (EF Core) when we go to connect to our own
database. We use EF Core because as the database complexity grows, so does the hassle of
not using an abstraction layer. The book discusses what it means to use an ORM, why you
would want to use one, and how to use EF Core. That being said, it is good to see how you
can connect to a SQL database in .NET Framework without an ORM.
To connect to a SQL database in C# without an ORM, we have to follow a couple of steps:
• Create a new SqlConnection object
• Open a connection to the database
• Specify the query we want to perform
• Execute our query
• Close our SqlConnection and query objects by disposing of them
Since the SqlConnection class implements the IDisposable interface, we need to dispose of
it after using it. If you are not familiar with garbage collection: disposing of an object means
we tell the garbage collector we do not need to use the object anymore and request that it
removes it from memory in the next garbage collection cycle. We only need to explicitly go
through this process for types that hold onto resources such as a SqlConnection (which can
hold onto an open connection to a database). If we do not dispose of such an object, chances
are it remains in memory for the duration of the application’s runtime. This is what we call a
memory leak. The easiest and most used way to dispose of an object is to wrap it in a using
statement. This scopes the object to that particular block of code and disposes of the object
when the code block is finished.
Next, we need to open the connection to our database. We do this by calling upon the
Open method of the SqlConnection instance. If you don’t “open” your SqlConnection, any
query fails since there is no open connection to the database. To use an opened connection,
we need a query to execute. To specify a query, we create a new instance of SqlCommand.
One of the available constructors for SqlCommand takes in a string. This string is the SQL
command you want to execute; in the case of listing 2.3 we want to select all records from a
table called “myTable”: “SELECT * FROM myTable”.
Then, we call the ExecuteScalar method on the SqlCommand containing our SELECT
query. There are a variety of ways you can execute a SqlCommand. ExecuteScalar returns a
single column of serialized data (one value). We store this data in a variable of type object
(all classes and types inherit from type object). You could further process this to a different
data structure if you want. Finally, since SqlCommand also implements IDisposable, we need
to dispose of it. If you don’t want to wrap a disposable object in a using block, an alternative
way is to explicitly call [object].Dispose when you are done with the instance. Listing 2.3
shows both approaches.
NOTE Most classes in the .NET Framework and C# use Pascal-Case style capitalization (concatenated words
all start with capitalized letters: SqlCommand) for methods and attribute names. Variables and properties (if
not public), however, use camel casing (each word after the first starts with a capital letter: tennisBall).
Recycling with C#
Figure 2.2 Recycling a disposable object in C#. Step 1: the class implements IDisposable. Step 2: We wrap it in
a “using” statement. Step 3: we dispose safely of the object. Just like in real-life recycling, disposing of
something safely is of paramount importance to the health of our environment.
time and time again. Luckily, the .NET Framework provides an excellent built-in CSV parser
that makes our life a lot easier.
Since the library exposed in the .NET Framework is not just meant for CSV files, it is called
TextFieldParser. It is part of the Microsoft.VisualBasic.FileIO namespace. You
might think, how can I use a library in Visual Basic in C#? Since many languages implement
the .NET Framework and compile down to the same Intermediate Language (discussed in
section 2.2), we can use code compiled against any languages using .NET in any other
language using .NET.
To parse a CSV file in C# using TextFieldParser, follow a couple of simple steps:
Starting with the first three items, create your TextFieldParser, give it the path to the file
(as a string), and wrap it in a using statement:
using (TextFieldParser parser = new TextFieldParser(myFilePathString))
{
…
}
Now we need to configure our parser. There are a myriad of options you can set (what your
comment tokens are, whether your data encloses fields in quotes, whether you want to trim
white space, what the field width is, and more) but we are most concerned with specifying
our delimiter character. We set our delimiter to a comma character but you can set it to any
character you want. You can also use multiple delimiters.
parser.SetDelimiters(","); #A
Before we can grab the fields from the file, we need to declare and initialize a collection to
store the information in:
We loop over the parser until its EndOfData property evaluates to true (it’s a Boolean), parse
the found data into a string array, and add the string array to parsedFields.
while (!parser.EndOfData)
{
string[] fields = parser.ReadFields();
parsedFields.Add(fields);
}
That, in a nutshell, is how you parse a CSV file in C#. You can, of course, process the data
further into an object of your liking. To wrap up, this is the complete code snippet:
2.1.5 Exercises
EXERCISE 2.1
Fill in the blanks: To connect to a SQL database, you can use an ORM such as _, or do it
yourself with the help of _.
a) True
b) False
EXERCISE 2.3
What does this error mean: “Cannot implicitly convert type bool to int”?
a) The code tries to convert an integer to a bool type. The compiler does not know
how to do this.
b) The code tries to convert a bool to an integer type. The compiler does not know
how to do this.
c) The code tried to optimize your code and generated an invalid conversion.
EXERCISE 2.4
True or False: Because the SqlConnection class implements the IDisposable interface, we
do not have to manually clean up any resources left by the SqlConnection logic.
not be copied over since other platforms would not have the same APIs. This made things
like working with graphics and GUIs tremendously difficult on a platform other than
Windows.
NOTE COM Interop is a technology (part of the CLR) that allows the .NET Framework to interact with COM
objects and vice versa. COM (Component Object Model) objects are low-level models, often written in C, used
as the basis for many internal Windows APIs.
The initial focus of .NET Core was put on web services. This removed the immediate concern
of graphics programming on a new platform, although movement in that space has been
made recently; there are third-party libraries that can help with GUI development on other
platforms, mainly by replacing the provided components with components compatible with
the native graphics APIs of a specific platform. Since .NET Core uses the Mono compiler (an
open-source .NET Core compiler created for Linux/Mac and the Unity video game engine),
there are differences in how code compiles between the .NET Framework and .NET Core
(.NET Framework uses the Roslyn compiler by default). Since .NET Core 3 adheres to the
.NET Standard, Windows Forms, Windows Presentation Foundation, and Universal Windows
Platform programs can target .NET Core 3. This, however, has not proven to be a hurdle for
the adoption of .NET Core. Many companies are using .NET Core for their web back-ends
such as services and APIs. Developers can write these back-ends once and run on Windows,
macOS (previously OSX), and Linux with the same code base
.NET Standard
The .NET Standard is a specification that has been used to develop a variety of implementations of .NET: .NET
Framework, .NET Core, Mono (the cross-platform technology that .NET Core is built on), Unity (video game
development), and Xamarin (iOS and Android development). These have different use-cases but are inherently very
similar. Developing an implementation against the .NET Standard means that code-sharing between implementations
is as seamless as possible.
The .NET Standard contains information on what APIs are available for use when interacting with the CLR (the
runtime on which C# depends). Before .NET Standard, there was no real way of making sure that your code or library
would work across .NET implementations besides using Portable Class Libraries (PCL). PCLs are libraries that can be
shared among projects but can only target a specific version of a .NET implementation (or “profile”). Today we call
these PCLs “profile-based PCLs.” Libraries targeting a .NET implementation adhering to the .NET Standard are also
PCLs, but instead of targeting a specific implementation, they target a version of the .NET Standard. To differentiate
between profile-based PCL’s, we call these “.NET Standard-based PCLs.” The .NET Standard encapsulates a lot of the
Windows APIs used by libraries written in the pre .NET Standard era (and therefore profile-based PCLs). As a result, we
can use those libraries in any .NET Standard implementation of .NET without a problem. The first version of the .NET
Framework to implement the .NET Standard was 4.5.
As with all modern .NET developments, the .NET Standard is fully open source. The code and documentation live
on GitHub (https://github.com/dotnet/standard).
.NET Core has transitioned from yet another spinoff into the future of the .NET ecosystem. In
fact, the next step in the .NET story is the merger between .NET Framework 4.x and .NET
Core 3.x. The next release of .NET is.NET 5, but in essence, it also is .NET Core 4, and it
replaces the current iteration of the .NET Framework. For any new development in .NET, I
highly recommend to use .NET Core 3 for now, but switch to .NET 5 when a public release
client is released. The reason for this is that you still get the most up-to-date version of .NET
Core with the least amount of work when it comes time to switch to .NET 5. All the lessons
learned in this book transfer over smoothly to .NET 5.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
textbookfull.com