Is there any difference between A and B?
Class A has private constructor:
class A
{
private A()
{ }
}
Class B is sealed and has a private constructor:
sealed class B
{
private B()
{ }
}
Private keyword is used for declaring class. Sealed: If a class is declared as sealed, that means that you cannot inherit from the class . Sealed class can be used when a class is internal to the operation of the library, class or whwn you donot want that class to be overridden because it may affect the functionality.
Sealed classes cannot be instantiated directly. Sealed classes cannot have public constructors (The constructors are private by default). Sealed classes can have subclasses, but they must either be in the same file or nested inside of the sealed class declaration.
If a class contains only private constructor without parameter, then it prevents the automatic generation of default constructor. If a class contains only private constructors and does not contain public constructor, then other classes are not allowed to create instances of that class except nested class.
In my opinion, private are used with in the class only where it was declared and static methods can be used any where by using static member. Private Constructor - This is the constructor whose access modifier is private. private constructor is used to prevent a class to be instantiated.
Yes A
can be inherited by a nested class, while B
cannot be inherited at all. This is perfectly legal:
public class A {
private A() { }
public class Derived : A { }
}
Note that any code could create a new A.Derived()
or inherit from A.Derived
(its constructor is public), but no other classes outside the source text of A
can inherit directly from A
.
A typical use for something like this is a class with enum-like values but which can have custom behavior:
public abstract class A {
private A() { }
public abstract void DoSomething();
private class OneImpl : A {
public override void DoSomething() { Console.WriteLine("One"); }
}
private class TwoImpl : A {
public override void DoSomething() { Console.WriteLine("Two"); }
}
public static readonly A One = new OneImpl();
public static readonly A Two = new TwoImpl();
}
There is one tiny difference you can get, to do with Code Analysis.
Consider this code:
public class Base
{
public virtual void Function()
{
}
}
public class Derived: Base
{
public static Derived Create()
{
return new Derived();
}
private Derived()
{
// Code analysis warning: CS2214 "Do not call overridable methods in constructors".
Function();
}
}
There is a Code Analysis warning for the Derived constructor, because we are accessing a virtual method from it, which is A Bad Thing.
However, if you make Derived
sealed, the Code Analysis warning goes away.
So there's a tiny and contrived difference for you. ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With