Deconstructors

Constructors allow you to take multiple parameters and encapsulate them all into a single object. Until now, we haven’t introduced any constructs for implementing the reverse—unwrapping the encapsulated item into its constituent parts. Sure, you could manually assign each property to a variable; however, if there were a significant number of such variables, it would require many separate statements. With tuples, however, this becomes significantly easier. You could, for example, declare a method like the Deconstruct() method shown in Listing 6.43.

Listing 6.43: Defining and Using a Deconstructor
public class Employee
{
    // ...
    public void Deconstruct(
        out int id, out string firstName, 
        out string lastName, out string? salary)
    {
       (id, firstName, lastName, salary) = 
            (Id, FirstName, LastName, Salary);
    }
    // ...
}
 
public class Program
{
    public static void Main()
    {
        Employee employee;
        employee = new ("Inigo""Montoya")
        {
            // Leveraging object initializer syntax
            Salary = "Too Little"
        };
        // ...
 
        employee.Deconstruct(out _, out string firstName,
            out string lastName, out string? salary);
 
        System.Console.WriteLine(
            "{0} {1}: {2}",
            firstName, lastName, salary);
    }
}

Such a method could be invoked directly, as one would expect from Chapter 5, by declaring the out parameters inline. However, you can invoke the Deconstruct() method—the deconstructor12—implicitly by assigning the object instance to a tuple directly as shown in Listing 6.44.

Listing 6.44: Implicitly Invoking Deconstructors
public class Program
{
    public static void Main()
    {
        Employee employee;
        employee = new ("Inigo""Montoya")
        {
            // Leveraging object initializer syntax
            Salary = "Too Little"
        };
 
        // ...
 
        (_, string firstName, string lastName, string? salary) = employee;
 
        System.Console.WriteLine(
            "{0} {1}: {2}",
            firstName, lastName, salary);
    }
}

The syntax results in the identical CIL code as that highlighted in Listing 6.43—it is just a simpler syntax (and a little less indicative that the Deconstruct() method is invoked). Note that the syntax allows for variables matching the out parameter assignments using tuple syntax. It does not allow for the assignment of a tuple type, either

(int, string, string, string) tuple = employee;

or with named items as in

(int id, string firstName, string lastName, string salary) tuple = employee

To declare a deconstructor, the method name must be Deconstruct and have a signature that returns void and exclusively accepts two or more out parameters. And, given such a signature, it is possible to assign an object instance directly to a tuple without the explicit method invocation.

Note that prior to C# 10, all the assigned values needed to be newly declared or pre-declared—you couldn’t mix newly declared with existing variables. With C# 10, this restriction was removed.

Static Members

The HelloWorld example in Chapter 1 briefly touched on the keyword static. This section defines the static keyword more fully.

First, let’s consider an example. Assume that the employee Id value needs to be unique for each employee. One way to accomplish this is to store a counter to track each employee ID. If the value is stored as an instance field, however, every time you instantiate an object, a new NextId field will be created such that every instance of the Employee object will consume memory for that field. The biggest problem is that each time an Employee object is instantiated, the NextId value on all of the previously instantiated Employee objects needs to be updated with the next ID value. In this case, what you need is a single field that all Employee object instances share.

Language Contrast: C++—Global Variables and Functions

Unlike many of the languages that came before it, C# does not have global variables or global functions. All fields and methods in C# appear within the context of a class. The equivalent of a global field or function within the realm of C# is a static field or function. There is no functional difference between global variables/functions and C# static fields/methods, except that static fields/methods can include access modifiers, such as private, that can limit the access and provide better encapsulation.

Static Fields

To define data that is available across multiple instances, you use the static keyword, as demonstrated in Listing 6.45.

Listing 6.45: Declaring a Static Field
public class Employee
{
    public Employee(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
        Id = NextId;
        NextId++;
    }
 
    // ...
 
    public static int NextId;
    public int Id { getprivate set; }
    public string FirstName { getset; }
    public string LastName { getset; }
    public string? Salary { getset; } = "Not Enough";
 
    // ...
}

In this example, the NextId field declaration includes the static modifier and therefore is called a static field. Unlike Id, a single storage location for NextId is shared across all instances of Employee. Inside the Employee constructor, you assign the new Employee object’s Id the value of NextId immediately before incrementing the Id. When another instance of the Employee class is created, NextId will be incremented, and the new Employee object’s Id field will hold a different value.

Just as instance fields (non-static fields) can be initialized at declaration time, so can static fields, as demonstrated in Listing 6.46.

Listing 6.46: Assigning a Static Field at Declaration
public class Employee
{
    // ...
    public static int NextId = 42;
    // ...
}

Unlike with instance fields, if no initialization for a static field is provided, the static field will automatically be assigned its default value (0, null, false, and so on)—the equivalent of default(T), where T is the name of the type. As a result, it will be possible to access the static field even if it has never been explicitly assigned in the C# code.

Non-static fields, or instance fields, provide a new storage location for each object to which they belong. In contrast, static fields don’t belong to the instance, but rather to the class itself. As a result, you access a static field from outside a class via the class name. Consider the new Program class shown in Listing 6.47 (using the Employee class from Listing 6.45 along with Output 6.8).

Listing 6.47: Accessing a Static Field
using System;
 
public class Program
{
    public static void Main()
    {
        Employee.NextId = 1000000;
 
        Employee employee1 = new(
            "Inigo""Montoya");
        Employee employee2 = new(
            "Princess""Buttercup");
 
        Console.WriteLine(
            "{0} {1} ({2})",
            employee1.FirstName,
            employee1.LastName,
            employee1.Id);
        Console.WriteLine(
            "{0} {1} ({2})",
            employee2.FirstName,
            employee2.LastName,
            employee2.Id);
 
        Console.WriteLine(
            $"NextId = {Employee.NextId}");
    }
    // ...
}
Output 6.8
Inigo Montoya (1000000)
Princess Buttercup (1000001)
NextId = 1000002

To set and retrieve the initial value of the NextId static field, you use the class name, Employee, rather than a reference to an instance of the type. The only place you can omit the class name is within the class itself (or a derived class). In other words, the Employee(...) constructor did not need to use Employee.NextId because the code appeared within the context of the Employee class itself, and therefore, the context was implied. The scope of a variable is the program context in which the variable can be referred to by its unqualified name; the scope of a static field is the context of the class (and any derived classes).

Even though you refer to static fields slightly differently than you refer to instance fields, it is not possible to define a static field and an instance field with the same name in the same class. The possibility of mistakenly referring to the wrong field is high, so the C# designers decided to prevent such code. Overlap in names, therefore, introduces conflict within the declaration space.

Beginner Topic
Data Can Be Associated with Both a Class and an Object

Both classes and objects can have associated data, just as can the molds and the widgets created from them.

For example, a mold could have data corresponding to the number of widgets it created, the serial number of the next widget, the current color of the plastic injected into the mold, and the number of widgets it produces per hour. Similarly, a widget has its own serial number, its own color, and perhaps the date and time when the widget was created. Although the color of the widget corresponds to the color of the plastic within the mold at the time the widget was created, it obviously does not contain data corresponding to the color of the plastic currently in the mold, or the serial number of the next widget to be produced.

In designing objects, programmers should take care to declare fields, properties, and methods appropriately, as static or instance based. In general, you should declare methods that don’t access any instance data as static methods. Static fields store data corresponding to the class, such as defaults for new instances or the number of instances that have been created. Instance fields store data associated with the object.

Static Methods

Just as with static fields, you access static methods directly off the class name—for example, as Console.ReadLine(). Furthermore, it is not necessary to have an instance to access the method.

Listing 6.48 provides another example of both declaring and calling a static method.

Listing 6.48: Defining a Static Method on DirectoryInfoExtension
public static class DirectoryInfoExtension
{
    public static void CopyTo(
        DirectoryInfo sourceDirectory, string target,
        SearchOption option, string searchPattern)
    {
        if (target[^1] !=
            Path.DirectorySeparatorChar)
        {
            target += Path.DirectorySeparatorChar;
        }
        Directory.CreateDirectory(target);
 
        for (int i = 0; i < searchPattern.Length; i++)
        {
            foreach (string file in
                Directory.EnumerateFiles(
                    sourceDirectory.FullName, searchPattern))
            {
                File.Copy(file,
                    target + Path.GetFileName(file), true);
            }
        }
 
        // Copy subdirectories (recursively)
        if (option == SearchOption.AllDirectories)
        {
            foreach (string element in
                Directory.EnumerateDirectories(
                    sourceDirectory.FullName))
            {
                Copy(element,
                    target + Path.GetFileName(element),
                    searchPattern);
            }
        }
    }
    // ...
}
 
public class Program
{
    public static void Main(params string[] args)
    {
        DirectoryInfo source = new(args[0]);
        string target = args[1];
 
        DirectoryInfoExtension.CopyTo(
            source, target,
            SearchOption.AllDirectories, "*");
    }
}

In Listing 6.48, the DirectoryInfoExtension.CopyTo() method takes a DirectoryInfo object and copies the underlying directory structure to a new location.

Because static methods are not referenced through a particular instance, the this keyword is invalid inside a static method. In addition, it is not possible to access either an instance field or an instance method directly from within a static method without a reference to the instance to which the field or method belongs. (Note that Main() is another example of a static method.)

One might have expected this method on the System.IO.Directory class or as an instance method on System.IO.DirectoryInfo. Since neither exists, Listing 6.48 defines such a method on an entirely new class. In the section “Extension Methods” later in this chapter, we show how to make it appear like an instance method on DirectoryInfo.

Static Constructors

In addition to static fields and methods, C# supports static constructors. Static constructors are provided as a means to initialize the class itself rather than the instances of a class. Such constructors are not called explicitly; instead, the runtime calls static constructors automatically upon first access to the class, whether by calling a regular constructor or by accessing a static method or field on the class. Because the static constructor cannot be called explicitly, no parameters are allowed on static constructors.

You use static constructors to initialize the static data within the class to a particular value, primarily when the initial value involves more complexity than a simple assignment at declaration time. Consider Listing 6.49.

Listing 6.49: Declaring a Static Constructor
public class Employee
{
    static Employee()
    {
        Random randomGenerator = new();
        NextId = randomGenerator.Next(101, 999);
    }
 
    // ...
    public static int NextId = 42;
    // ...
}

Listing 6.49 assigns the initial value of NextId to be a random integer between 100 and 1,000. Because the initial value involves a method call, the NextId initialization code appears within a static constructor and not as part of the declaration.

If assignment of NextId occurs within both the static constructor and the declaration, it is not obvious what the value will be when initialization concludes. The C# compiler generates CIL in which the declaration assignment is moved to be the first statement within the static constructor. Therefore, NextId will contain the value returned by randomGenerator.Next(101, 999) instead of a value assigned during NextId’s declaration. Assignments within the static constructor, therefore, will take precedence over assignments that occur as part of the field declaration, as was the case with instance fields. Note that there is no support for defining a static finalizer.

Be careful not to throw an exception from a static constructor, as this will render the type unusable for the remainder of the application’s lifetime.13

AdVanced Topic
Favor Static Initialization during Declaration

Static constructors execute before the first access to any member of a class, whether it is a static field, another static member, or an instance constructor. To support this practice, the runtime checks that all static members and constructors to ensure that the static constructor runs first.

Without the static constructor, the compiler initializes all static members to their default values and avoids adding the static constructor check. The result is that static assignment initialization is called before any static fields are accessed but not necessarily before all static methods or any instance constructor is invoked. This might provide a performance improvement if initialization of static members is expensive and is not needed before accessing a static field. For this reason, you should consider either initializing static fields inline rather than using a static constructor or initializing them at declaration time.

Guidelines
CONSIDER initializing static fields inline rather than explicitly using static constructors or declaration assigned values.
Static Properties

You also can declare properties as static. For example, Listing 6.50 wraps the data for the next ID into a property.

Listing 6.50: Declaring a Static Property
public class Employee
{
    // ...
    public static int NextId
    {
        get
        {
            return _NextId;
        }
        private set
        {
            _NextId = value;
        }
    }
    public static int _NextId = 42;
    // ...
}

It is almost always better to use a static property rather than a public static field, because public static fields are callable from anywhere, whereas a static property offers at least some level of encapsulation.

The entire NextId implementation—including an inaccessible backing field—can be simplified to an automatically implemented property with an initializer:14

public static int NextId { get; private set; } = 42;

Static Classes

Some classes do not contain any instance fields. Consider, for example, a SimpleMath class that has functions corresponding to the mathematical operations Max() and Min(), as shown in Listing 6.51.

Listing 6.51: Declaring a Static Class
public static class SimpleMath
{
    // params allows the number of parameters to vary
    public static int Max(params int[] numbers)
    {
        // Check that there is at least one item in numbers
        if(numbers.Length == 0)
        {
            throw new ArgumentException(
                "numbers cannot be empty"nameof(numbers));
        }
 
        int result;
        result = numbers[0];
        foreach(int number in numbers)
        {
            if(number > result)
            {
                result = number;
            }
        }
        return result;
    }
 
    // params allows the number of parameters to vary
    public static int Min(params int[] numbers)
    {
        // Check that there is at least one item in numbers
        if(numbers.Length == 0)
        {
            throw new ArgumentException(
                "numbers cannot be empty"nameof(numbers));
        }
 
        int result;
        result = numbers[0];
        foreach(int number in numbers)
        {
            if(number < result)
            {
                result = number;
            }
        }
        return result;
    }
}
 
public class Program
{
    public static void Main(string[] args)
    {
        int[] numbers = new int[args.Length];
        for (int index = 0; index < args.Length; index++)
        {
            numbers[index] = args[index].Length;
        }
 
        Console.WriteLine(
            $@"Longest argument length = {
                Max(numbers) }");
 
        Console.WriteLine(
            $@"Shortest argument length = {
                Min(numbers) }");
    }
}

This class does not have any instance fields (or methods), so the creation of such a class would be pointless. Consequently, the class is decorated with the static keyword. The static keyword on a class provides two benefits. First, it prevents a programmer from writing code that instantiates the SimpleMath class. Second, it prevents the declaration of any instance fields or methods within the class. Because the class cannot be instantiated, instance members would be pointless. The Program class in prior listings is another good candidate for a static class because it, too, contains only static members.

Another distinguishing characteristic of the static class is that the C# compiler automatically marks it as abstract and sealed within the CIL. This designates the class as inextensible; in other words, no class can be derived from this class or even instantiate it. (The sealed and abstract keywords are covered in more detail in Chapter 7.)

In Chapter 5, we saw that the using static directive can be used with static classes such as SimpleMath. For example, adding a using static SimpleMath; declarative at the top of Listing 6.51 would allow you to invoke Max without the SimpleMath prefix:

       Console.WriteLine(

           $@"Longest argument length = { Max(numbers) }");

________________________________________

12. Introduced in C# 7.0.
13. Technically the application domain’s lifetime—the Common Language Runtime’s virtual equivalent of an operating system process.
14. Starting in C# 6.0.
{{ snackbarMessage }}