Static Classes, Partials and the nameof Operator

Static Classes, Partials and the nameof Operator

Static Classes and Partials

We have explored the basic concepts of classes and object. We will build on this understanding in this tutorial by learning about statics and partials.

Static Classes

A static class is a type of class that cannot be instantiated, you cannot create an object with this type. Throughout these tutorials, we frequently use a static class to output to the console via the writeline method. Conveniently this class is called Console.

Class vs a static class and usage

A class can be made static by including the keyword ‘static’ before its name. All members (both fields and methods) can be accessed directly from the class without the need for an instance object.

Partial Types

Partial types, which are often class, structs or interfaces, can be defined across multiple files which may be particularly useful when you are working on a large project.

Each instance that references the type must have the word partial before it – otherwise, the compiler will throw an error.

public partial class Car
{
    public void Drive()
    {
    }
}

public partial class Car
{
    public void Brake()
    {
    }
}

Partials must have the same level of accessibility, as the compiler will effectively combine these partials into one class which cannot have multiple access levels.

Partials are a common occurrence if you work with an IDE or tools that support class templating.

The nameof Expression

Calling ‘nameof’ on a variable or type will return the name of that variable/type as a usable string.


                    using System;

public class Program
{
	public static void Main()
	{
		int newNumber = 2;
		Console.WriteLine(nameof(newNumber));
	}
}
                

The nameof expression can also be called on members of an object. For example if you were to call nameof on the length property, nameof would return just the name ‘length’.

If you would like to learn more about the nameof operator then please visit the Microsoft C# documentation.