Reader small image

You're reading from  C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition

Product typeBook
Published inNov 2023
PublisherPackt
ISBN-139781837635870
Edition8th Edition
Right arrow
Author (1)
Mark J. Price
Mark J. Price
author image
Mark J. Price

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Read more about Mark J. Price

Right arrow

Join our book community on Discord

https://packt.link/EarlyAccess

Qr code Description automatically generated

This chapter is about some common types that are included with .NET. These include types for manipulating numbers, text, and collections; improving working with spans, indexes, and ranges; and in an optional online-only section, working with network resources.This chapter covers the following topics:

  • Working with numbers
  • Working with text
  • Pattern matching with regular expressions
  • Storing multiple objects in collections
  • Working with spans, indexes, and ranges

Working with numbers

One of the most common types of data is numbers. The most common types in .NET for working with numbers are shown in Table 8.1:

Namespace Example type(s) Description
System SByte , Int16 , Int32 , Int64 , Int128 Integers; that is, zero, and positive and negative whole numbers.
System Byte , UInt16 , UInt32 , UInt64 , UInt128 Cardinals; that is, zero and positive whole numbers.
System Half , Single , Double Reals; that is, floating-point numbers.
System Decimal Accurate reals; that is, for use in science, engineering, or financial scenarios.
System.Numerics BigInteger , Complex , Quaternion Arbitrarily large integers, complex numbers, and quaternion numbers.
Table 8.1: Common .NET number types

.NET has had the 32-bit float and 64-bit double types since .NET Framework 1.0 was released in 2002. The IEEE 754 specification also defines a 16-bit floating-point standard. Machine learning and other algorithms would benefit from this smaller, lower-precision...

Working with text

One of the other most common types of data for variables is text. The most common types in .NET for working with text are shown in Table 8.2:

Namespace Type Description
System Char Storage for a single text character
System String Storage for multiple text characters
System.Text StringBuilder Efficiently manipulates strings
System.Text.RegularExpressions Regex Efficiently pattern-matches strings
Table 8.2: Common .NET types for working with text

Getting the length of a string

Let's explore some common tasks when working with text; for example, sometimes you need to find out the length of a piece of text stored in a string variable:

  1. Use your preferred code editor to add a new Console App / console project named WorkingWithText to the Chapter08 solution.
  2. In the WorkingWithText project, in Program.cs, delete the existing statements and then add statements to define a variable to store the name of the city London, and then write its name and length to...

Pattern matching with regular expressions

Regular expressions are useful for validating input from the user. They are very powerful and can get very complicated. Almost all programming languages have support for regular expressions and use a common set of special characters to define them.Let's try out some example regular expressions:

  1. Use your preferred code editor to add a new Console App / console project named WorkingWithRegularExpressions to the Chapter08 solution.
  2. In Program.cs, delete the existing statements and then import the following namespace:
using System.Text.RegularExpressions; // To use Regex.

Checking for digits entered as text

We will start by implementing the common example of validating number input:

  1. In Program.cs, add statements to prompt the user to enter their age and then check that it is valid using a regular expression that looks for a digit character, as shown in the following code:
Write("Enter your age: ");
string input = ReadLine()...

Storing multiple objects in collections

Another of the most common types of data is collections. If you need to store multiple values in a variable, then you can use a collection.A collection is a data structure in memory that can manage multiple items in different ways, although all collections have some shared functionality.The most common types in .NET for working with collections are shown in Table 8.8:

Working with spans, indexes, and ranges

One of Microsoft's goals with .NET Core 2.1 was to improve performance and resource usage. A key .NET feature that enables this is the Span<T> type.

Using memory efficiently using spans

When manipulating arrays, you will often create new copies or subsets of existing ones so that you can process just the subset. This is not efficient because duplicate objects must be created in memory.If you need to work with a subset of an array, use a span because it is like a window into the original array. This is more efficient in terms of memory usage and improves performance. Spans only work with arrays, not collections, because the memory must be contiguous.Before we look at spans in more detail, we need to understand some related objects: indexes and ranges.

Identifying positions with the Index type

C# 8 introduced two features for identifying an item's index position within an array and a range of items using two indexes.You learned...

Practicing and exploring

Test your knowledge and understanding by answering some questions, getting some hands-on practice, and exploring with deeper research into the topics in this chapter.

Exercise 8.1 – Test your knowledge

Use the web to answer the following questions:

  1. What is the maximum number of characters that can be stored in a string variable?
  2. When and why should you use a SecureString type?
  3. When is it appropriate to use a StringBuilder class?
  4. When should you use a LinkedList<T> class?
  5. When should you use a SortedDictionary<T> class rather than a SortedList<T> class?
  6. In a regular expression, what does $ mean?
  7. In a regular expression, how can you represent digits?
  8. Why should you not use the official standard for email addresses to create a regular expression to validate a user's email address?
  9. What characters are output when the following code runs?
string city = "Aberdeen";
ReadOnlySpan<char> citySpan = city.AsSpan()[^5..^0]...

Summary

In this chapter, you explored:

  • Choices for types to store and manipulate numbers.
  • Handling text, including using regular expressions for validating input.
  • Collections to use for storing multiple items.
  • Working with indexes, ranges, and spans.

In the next chapter, we will manage files and streams, encode and decode text, and perform serialization.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781837635870
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Author (1)

author image
Mark J. Price

Mark J. Price is a Microsoft Specialist: Programming in C# and Architecting Microsoft Azure Solutions, with over 20 years' experience. Since 1993, he has passed more than 80 Microsoft programming exams and specializes in preparing others to pass them. Between 2001 and 2003, Mark was employed to write official courseware for Microsoft in Redmond, USA. His team wrote the first training courses for C# while it was still an early alpha version. While with Microsoft, he taught "train-the-trainer" classes to get other MCTs up-to-speed on C# and .NET. Mark holds a Computer Science BSc. Hons. Degree.
Read more about Mark J. Price

Namespace Example type(s) Description
System .Collections IEnumerable ,
IEnumerable<T>
Interfaces and base classes used by collections.
System .Collections .Generic List<T> ,
Dictionary<T> ,
Queue<T> ,
Stack<T>
Introduced in C# 2.0 with .NET Framework 2.0. These collections allow you to specify the type you want to store using a generic type parameter (which is safer, faster, and more efficient).
System .Collections .Concurrent BlockingCollection ,
ConcurrentDictionary ,
ConcurrentQueue
These collections are safe to use in multithreaded scenarios...