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

Inheriting from classes

The Person type we created earlier derived (inherited) from System.Object. Now, we will create a subclass that inherits from Person:

  1. In the PacktLibrary project, add a new class file named Employee.cs.
  2. Modify its contents to define a class named Employee that derives from Person, as shown in the following code:
namespace Packt.Shared;
public class Employee : Person
{
}
  1. In the PeopleApp project, in Program.cs, add statements to create an instance of the Employee class, as shown in the following code:
Employee john = new()
{
  Name = "John Jones",
  Born = new(year: 1990, month: 7, day: 28,
    hour: 0, minute: 0, second: 0, offset: TimeSpan.Zero))
};
john.WriteToConsole();
  1. Run the PeopleApp project and view the result, as shown in the following output:
John Jones was born on a Saturday.

Note that the Employee class has inherited all the members of Person.

Extending classes to add functionality

Now, we will add some employee-specific members...

Casting within inheritance hierarchies

Casting between types is subtly different from converting between types. Casting is between similar types, like between a 16-bit integer and a 32-bit integer, or between a superclass and one of its subclasses. Converting is between dissimilar types, such as between text and a number.For example, if you need to work with multiple types of stream, then instead of declaring specific types of stream like MemoryStream or FileStream, you could declare an array of Stream, the supertype of MemoryStream and FileStream.

Implicit casting

In the previous example, you saw how an instance of a derived type can be stored in a variable of its base type (or its base's base type, and so on). When we do this, it is called implicit casting.

Explicit casting

The opposite of implicit casting is explicit casting, and you must use parentheses around the type you want to cast into as a prefix to do it:

  1. In Program.cs, add a statement to assign the aliceInPerson variable...

6 Implementing Interfaces and Inheriting Classes

Join our book community on Discord

https://packt.link/EarlyAccess

Qr code Description automatically generated

This chapter is about deriving new types from existing ones using object-oriented programming (OOP). You will learn how to use operators as an alternative method to implement simple functionality, and you will learn how to use generics to make your code safer and more performant. You will learn about delegates and events to exchange messages between types. You will see the differences between reference and value types. You will implement interfaces for common functionality. You will create a derived class to inherit from a base class to reuse functionality, override an inherited type member, and use polymorphism. Finally, you will learn how to create extension methods and cast between classes in an inheritance hierarchy.This chapter covers the following topics:

  • Setting up a class library and console application
  • Static methods and overloading operators
  • Making types safely...

Summarizing custom type choices

Now that we have covered OOP and the C# features that enable you to define your own types, let's summarize what you've learned.

Categories of custom type and their capabilities

Categories of custom type and their capabilities are summarized in the following table:

Type Instantiation Inheritance Equality Memory
class Yes Single Reference Heap
sealed class Yes None Reference Heap
abstract class No Single Reference Heap
record or record class Yes Single Value Heap
struct or record struct Yes None Value Stack
interface No Multiple Reference Heap

It is best to think about these differences by starting with the "normal" case and then spotting the differences in other cases. For example, a "normal" class can be instantiated with new, it supports single inheritance, it uses memory reference equality, and its state is stored in heap memory.Now let's highlight what is different about the more specialized types...

Practicing and exploring

Test your knowledge and understanding by answering some questions, getting some hands-on practice, and exploring this chapter's topics with more in-depth research.

Exercise 6.1 – Test your knowledge

Answer the following questions:

  1. What is a delegate?
  2. What is an event?
  3. How are a base class and a derived class related, and how can the derived class access the base class?
  4. What is the difference between is and as operators?
  5. Which keyword is used to prevent a class from being derived from or a method from being further overridden?
  6. Which keyword is used to prevent a class from being instantiated with the new keyword?
  7. Which keyword is used to allow a member to be overridden?
  8. What's the difference between a destructor and a deconstruct method?
  9. What are the signatures of the constructors that all exceptions should have?
  10. What is an extension method, and how do you define one?

Exercise 6.2 – Practice creating an inheritance hierarchy

Explore...

Summary

In this chapter, you learned about:

  • Operators
  • Generic types
  • Delegates and events
  • Implementing interfaces
  • Memory usage differences between reference and value types
  • Working with null values
  • Deriving and casting types using inheritance
  • Base and derived classes, how to override a type member, and using polymorphism

In the next chapter, you will learn how .NET is packaged and deployed, and in subsequent chapters, the types that it provides you with to implement common functionality, such as file handling and database access.

Packaging your libraries for NuGet distribution

Before we learn how to create and package our own libraries, we will review how a project can use an existing package.

Referencing a NuGet package

Let’s say that you want to add a package created by a third-party developer, for example, Newtonsoft.Json, a popular package for working with the JavaScript Object Notation (JSON) serialization format:

  1. In the AssembliesAndNamespaces project, add a reference to the Newtonsoft.Json NuGet package, either using the GUI for Visual Studio 2022 or the dotnet add package command for Visual Studio Code.
  2. Open the AssembliesAndNamespaces.csproj file and note that a package reference has been added, as shown in the following markup:
    <ItemGroup>
      <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
    </ItemGroup>
    

If you have a more recent version of the Newtonsoft.Json package, then it has been updated...

Working with preview features

It is a challenge for Microsoft to deliver some new features that have cross-cutting effects across many parts of .NET like the runtime, language compilers, and API libraries. It is the classic chicken and egg problem. What do you do first?

From a practical perspective, it means that although Microsoft might have completed most of the work needed for a feature, the whole thing might not be ready until very late in their now annual cycle of .NET releases, too late for proper testing in “the wild.”

So, from .NET 6 onward, Microsoft will include preview features in general availability (GA) releases. Developers can opt into these preview features and provide Microsoft with feedback. In a later GA release, they can be enabled for everyone.

It is important to note that this topic is about preview features. This is different from a preview version of .NET or a preview version of Visual Studio 2022. Microsoft releases preview...

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 of this chapter.

Exercise 7.1 – Test your knowledge

Answer the following questions:

  1. What is the difference between a namespace and an assembly?
  2. How do you reference another project in a .csproj file?
  3. What is the benefit of a tool like ILSpy?
  4. Which .NET type does the C# float alias represent?
  5. When porting an application from .NET Framework to .NET 6, what tool should you run before porting, and what tool could you run to perform much of the porting work?
  6. What is the difference between framework-dependent and self-contained deployments of .NET applications?
  7. What is a RID?
  8. What is the difference between the dotnet pack and dotnet publish commands?
  9. What types of applications written for the .NET Framework can be ported to modern .NET?
  10. ...

Summary

In this chapter, we:

  • Reviewed the journey of .NET 8 for BCL functionality.
  • Explored the relationship between assemblies and namespaces.
  • Saw options for publishing an app for distribution to multiple operating systems.
  • Learned how to publish to native AOT for faster startup and smaller memory footprint.
  • Learned how to decompile .NET assemblies for educational purposes.
  • Packaged and distributed a class library.
  • Learned how to activate preview features.

In the next chapter, you will learn about some common BCL types that are included with modern .NET.

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 ₹800/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