Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

Static Classes

So far, you have seen the static modifier applied to constructors, fields, methods, and properties. You can also apply the static modifier to a class, which defines a static class. A static class can have only a static constructor, and as a result, it is not possible to create an instance of a static class. For that reason, static classes most commonly contain utility or helper methods that do not require a class instance to work.

Extension Methods

Extension methods are regular static methods, but the first parameter includes the this modifier and represents the type instance being extended, typically called the type extension parameter. Extension methods must be declared in a non-nested, non-generic static class.

When the namespace containing an extension class is in scope through a using directive, the extension methods appear as if they were native instance methods on the extended type. This allows them to be called in a natural and intuitive manner.

Because an extension method is nothing more than a specially marked static method, it does not have any special access to the type being extended and can work only with the public interface of the extended type. It also enables you to call the extension method in the more traditional way by referring to its fully qualified name.

Although an extension method matching the signature of an actual method on the type can be defined, it will not be visible. The compiler ensures that during method resolution, any actual class methods take precedence over extension methods. This ensures that an extension method cannot change the behavior of a standard class method, which would cause unpredictable, or at least unexpected, behavior.

  • + Share This
  • 🔖 Save To Your Account