sealed class, with private constructor, versus static class

8

By "studying" this class , I checked that it is sealed and has the private constructor:

public sealed class Interaction
{
    /// <remarks>
    /// CA1053: Static holder types should not have public constructors
    /// </remarks>
    private Interaction()
    {

    }

    //Vários métodos estáticos públicos e privados
    ...
    ...
}

Declare it static and "remove" the constructor

public static class Interaction
{

    //Vários métodos estáticos públicos e privados
    ...
    ...
}

changes in some way how it can be used / consumed?

    
asked by anonymous 11.01.2017 / 16:25

1 answer

6

The main difference is that the static class can not even be instantiated. A normal class with private constructor just does not let some code outside the class instantiate it, but it can be instantiated internally, after all its static methods can access that constructor.

This works:

using static System.Console;

public class Program {
    public static void Main(){
        var instancia = Instancia.Factory();
        WriteLine(instancia.GetType());
    }
}

public class Instancia {
    private Instancia() {}
    public static Instancia Factory() {
        return new Instancia();
    }
}

See working on .NET Fiddle . And at Coding Ground . Also I placed in Github for future reference .

This internal instance can be only internally or can be made available externally for those who want to use it, it depends on how it was coded.

It is even possible to publicly call this private constructor in less orthodox ways, with reflection, for example.

Another difference is that the normal class may have non-static members. And that may even make sense knowing that it can be instantiated.

Just remembering that if there is a static construct in any of the classes, it will be called sometime before its use. The normal class constructor will only be called by code. It is even possible for a static constructor of the normal class to be used to create an internal instance.

A technical detail is that static classes are both sealed and abstract , you can check this in CIL.

Why prefer static class where it makes sense

If the people involved in the code do not do anything crazy, the normal class with private constructor can function as the static class, but it depends on following the convention. It would be much better to secure this via code. And let's face it, if you say it's static, it gives you the right message of what it is.

I think people use this technique here and there because C # 1 had no static class, just like Java. You no longer have to do this, unless you have a good reason or want to use some trick that can justify it.

This "trick" is often used to create Singleton .

    
11.01.2017 / 17:02