...

/

Inheriting and Extending .NET Types

Inheriting and Extending .NET Types

Learn about inheriting exceptions in .NET to create custom exception types and extend existing types using static and extension methods for added functionality.

.NET has pre-built class libraries containing hundreds of thousands of types. Rather than creating our own completely new types, we can often get a head start by deriving from one of Microsoft’s types to inherit some or all of its behavior and then overriding or extending it.

Inheriting exceptions

As an example of inheritance, we will derive a new type of exception:

Step 1: In the PacktLibrary project, add a new class file named PersonException.cs.

Step 2: Modify the contents of the file to define a class named PersonException with three constructors, as shown in the following code:

Press + to interact
namespace Packt.Shared;
public class PersonException : Exception
{
public PersonException() : base() { }
public PersonException(string message) : base(message) { }
public PersonException(string message, Exception innerException)
: base(message, innerException) { }
}

Unlike ordinary methods, constructors are not inherited, so we must explicitly declare and explicitly call the base constructor implementations in the System.Exception (or whichever exception class we derived from) to make them available to programmers who might want to use those constructors with our custom exception.

Step 3: In Person.cs ...