Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
C# 12 and .NET 8 – Modern Cross-Platform Development Fundamentals - Eighth Edition

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

Product type Book
Published in Nov 2023
Publisher Packt
ISBN-13 9781837635870
Pages 828 pages
Edition 8th Edition
Languages
Author (1):
Mark J. Price Mark J. Price
Profile icon Mark J. Price

Table of Contents (18) Chapters

Preface 1. Hello, C#! Welcome, .NET! 2. Speaking C# 3. Controlling Flow, Converting Types, and Handling Exceptions 4. Writing, Debugging, and Testing Functions 5. Building Your Own Types with Object-Oriented Programming 6. Implementing Interfaces and Inheriting Classes 7. Packaging and Distributing .NET Types 8. Working with Common .NET Types 9. Working with Files, Streams, and Serialization 10. Working with Data Using Entity Framework Core 11. Querying and Manipulating Data Using LINQ 12. Introducing Web Development Using ASP.NET Core 13. Building Websites Using ASP.NET Core Razor Pages 14. Building and Consuming Web Services 15. Building User Interfaces Using Blazor 16. Epilogue 17. Index

Unit testing

Fixing bugs in code is expensive. The earlier that a bug is discovered in the development process, the less expensive it will be to fix.Unit testing is a good way to find bugs early in the development process because they test a small unit before they are integrated together or are seen by user acceptance testers. Some developers even follow the principle that programmers should create unit tests before they write code, and this is called Test-Driven Development (TDD).Microsoft has a proprietary unit testing framework known as MSTest. There is also a framework named NUnit. However, we will use the free and open-source third-party framework xUnit.net. All three do basically the same thing. xUnit was created by the same team that built NUnit, but they fixed the mistakes they felt they made previously. xUnit is more extensible and has better community support.

If you are curious about the pros and cons of the various testing systems, then there are hundreds of articles written...

Throwing and catching exceptions in functions

In Chapter 3, Controlling Flow, Converting Types, and Handling Exceptions, you were introduced to exceptions and how to use a try-catch statement to handle them. But you should only catch and handle an exception if you have enough information to mitigate the issue. If you do not, then you should allow the exception to pass up through the call stack to a higher level.

Understanding usage errors and execution errors

Usage errors are when a programmer misuses a function, typically by passing invalid values as parameters. They could be avoided by that programmer changing their code to pass valid values. When some programmers first learn C# and .NET, they sometimes think exceptions can always be avoided because they assume all errors are usage errors. Usage errors should all be fixed before production runtime.Execution errors are when something happens at runtime that cannot be fixed by writing "better" code. Execution errors can be...

Practicing and exploring

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

Exercise 4.1 – Test your knowledge

Answer the following questions. If you get stuck, try googling the answers, if necessary, while remembering that if you get totally stuck, the answers are in the Appendix:

  1. What does the C# keyword void mean?
  2. What are some differences between imperative and functional programming styles?
  3. In Visual Studio Code or Visual Studio, what is the difference between pressing F5, Ctrl or Cmd + F5, Shift + F5, and Ctrl or Cmd + Shift + F5?
  4. Where does the Trace.WriteLine method write its output to?
  5. What are the five trace levels?
  6. What is the difference between the Debug and Trace classes?
  7. When writing a unit test, what are the three "A"s?
  8. When writing a unit test using xUnit, which attribute must you decorate the test methods with?
  9. What dotnet command...

Summary

In this chapter, you learned:

  • How to write reusable functions with input parameters and return values, in both an imperative and functional style.
  • How to use the Visual Studio and Visual Studio Code debugging and diagnostic features like logging and unit tests to identify and fix any bugs in them.
  • How to throw and catch exceptions in functions and understand the call stack.

In the next chapter, you will learn how to build your own types using object-oriented programming techniques.

Working with methods and tuples

Methods are members of a type that execute a block of statements. They are functions that belong to a type.

Returning values from methods

Methods can return a single value or nothing:

  • A method that performs some actions but does not return a value indicates this with the void type before the name of the method.
  • A method that performs some actions and returns a value indicates this with the type of the return value before the name of the method.

For example, in the next task, you will create two methods:

  • WriteToConsole: This will perform an action (writing some text to the console), but it will return nothing from the method, indicated by the void keyword.
  • GetOrigin: This will return a text value, indicated by the string keyword.

Let’s write the code:

  1. In Person.cs, add statements to define the two methods that I described earlier, as shown in the following code:
    #region...

Controlling access with properties and indexers

Earlier, you created a method named GetOrigin that returned a string containing the name and origin of the person. Languages such as Java do this a lot. C# has a better way, and it is called properties.

A property is simply a method (or a pair of methods) that acts and looks like a field when you want to get or set a value, but it acts like a method, thereby simplifying the syntax and enabling functionality, like validation and calculation, when you set and get a value.

A fundamental difference between a field and a property is that a field provides a memory address to data. You could pass that memory address to an external component, like a Windows API C-style function call, and it could then modify the data. A property does not provide a memory address to its data, which provides more control. All you can do is ask the property to get or set the data. The property then executes statements and can decide how to respond...

Pattern matching with objects

In Chapter 3, Controlling Flow, Converting Types, and Handling Exceptions, you were introduced to basic pattern matching. In this section, we will explore pattern matching in more detail.

Pattern-matching flight passengers

In this example, we will define some classes that represent various types of passengers on a flight, and then we will use a switch expression with pattern matching to determine the cost of their flight:

  1. In the PacktLibraryNetStandard2 project/folder, add a new file named FlightPatterns.cs.
  2. If you use Visual Studio 2022, in FlightPatterns.cs, delete the existing statements, including the class named FlightPatterns, because we will define multiple classes, and none match the name of the code file.
  3. In FlightPatterns.cs, add statements to define three types of passenger with different properties, as shown in the following code:
    // All the classes in this file will be defined in the following namespace...

Working with record types

Before we dive into the new record language feature, let us see some other related new features of C# 9 and later.

Init-only properties

You have used object initialization syntax to instantiate objects and set initial properties throughout this chapter. Those properties can also be changed after instantiation.

Sometimes, you want to treat properties like readonly fields so that they can be set during instantiation but not after. In other words, they are immutable. The init keyword enables this. It can be used in place of the set keyword in a property definition.

Since this is a language feature not supported by .NET Standard 2.0, we cannot use it in the PacktLibraryNetStandard2 project. We must use it in the modern project:

  1. In the PacktLibraryModern project, add a new file named Records.cs.
  2. In Records.cs, define a person class with two immutable properties, as shown in the following code:
    namespace Packt.Shared;
    public...

Practicing and exploring

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

Exercise 5.1 – Test your knowledge

Answer the following questions:

  1. What are the seven access modifier keywords and combinations of keywords, and what do they do?
  2. What is the difference between the static, const, and readonly keywords when applied to a type member?
  3. What does a constructor do?
  4. Why should you apply the [Flags] attribute to an enum type when you want to store combined values?
  5. Why is the partial keyword useful?
  6. What is a tuple?
  7. What does the record keyword do?
  8. What does overloading mean?
  9. What is the difference between the following two statements? (Do not just say a “>” character!)
    public List<Person> Children = new();
    public List<Person> Children => new();
    
  10. ...

Summary

In this chapter, you learned about:

  • Making your own types using OOP.
  • Some of the different categories of members that a type can have, including fields to store data and methods to perform actions.
  • OOP concepts, such as aggregation and encapsulation
  • How to use modern C# features, like relational and property pattern matching enhancements, init-only properties, and record types.

In the next chapter, you will take these concepts further by defining operators, delegates, and events, implementing interfaces, and inheriting from existing classes.

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 2023 Publisher: Packt ISBN-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.
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}