How are static constructors and private constructors different? - c#

How are static constructors and private constructors different?
public class WorkstationDevicePresenter
{
private WorkstationDevicePresenter()
{}
}
What's the point in leaving them blank?

Whats the point in leaving them blank?
There are a number of reasons to make "blank" constructors.
You might make a blank constructor because you want a place to set a breakpoint during debugging.
You might make a blank static constructor because doing so changes the semantics of static field initializers. Read Jon's article on the subject for details.
Let's leave static constructors and consider blank instance constructors.
The key rule that motivates blank constructors is: By default if there are no constructors in a type then you get a "blank" parameterless public constructor for free. If there are any constructors in a type then you do not get a blank parameterless public constructor for free.
So the first obvious reason why you'd want a blank constructor is: I want a blank parameterless constructor, but I've already made another ctor, so I no longer get one for free.
The second reason is that you don't have any ctors and you do not want a blank parameterless public constructor. You might want a blank parameterless private, internal or protected constructor. If that's what you want then you'll have to make one yourself.
In particular, making an empty private ctor as the only ctor means that the class cannot be instantiated via a constructor from outside the class. This is very useful if you want to use the factory pattern. It also prevents code outside the class from making derived classes, because derived classes must be able to call a constructor. If all the constructors are private then they can't derive.
I frequently use this variation on the factory pattern:
public abstract class Thing
{
private Thing() {}
private class RedThing : Thing { ... }
public static Thing GetRedThing() { return new RedThing(); }
}
See, by making a private constructor I can make a public abstract class that can only be instantiated by my code and only extended by my code, and therefore I have a nice invariant: every time I see an object of type Thing, I know where it came from.

Static constructors happen once when the class is loaded, private constructors happen when they are called by some public static method typically used to create singletons, or with the Builder pattern. There is no reason to have a blank private constructor (that I know of).

Static constructors initialize the static parts of a class and private constructors can only be used by the class itself, like for creating a singleton-object of the class.
public class MyClass {
private static int staticitem;
private int instanceitem;
static MyClass(){
staticitem = 0; //define value for staticitem
}
private MyClass() { //can only be called from within the class
instanceitem = 0; //define value for instanceitem
}
public static MyClass GetMyClass() {
MyClass m = new MyClass();
return m;
}
}

Blank private constructor will make the class uninstantiable by anything other than itself. If you don't have this piece of code, by default the compiler creates a blank public parameterless contstructor.
Static constructor is called when creating the static instance.
You can use both to create a Singleton pattern, for instance.
Check the following code:
public class Singleton
{
public static Singleton Instance;
static Singleton
{
Instance = new Singleton();
}
private Singleton()
{
}
}
public class SomeOtherClass
{
public static Singleton CompileError = new Singleton();
public static Singleton CompileOK = Singleton.Instance;
}

Related

Static constructor - Singleton Design pattern in c#

What if, I replaced private constructor with a static constructor in singleton Design pattern?
public sealed class Singleton
{
private static Singleton instance=null;
private Singleton()
{
}
public static Singleton Instance
{
get
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
Static constructor will be called only once and I couldn't find any difference in the implementation. Can we replace private with static constructor?
All that the private constructor is really doing in this case is preventing anything outside of the class from instantiating an instance of class Singleton, which is almost certainly intentional as a singleton should only have a single instance.
Static class constructors are run once for a type, at an unknown time, before the type, or any of it's static members, is to be utilized. Static fields are initialized before the static constructor would be run.
So, I suppose you could replace the constructor with a static one, but that would then give you the implicit parameter-less constructor on the Singleton Type, which would allow anyone to instantiate an instance, which is likely at odds with why you are using the singleton pattern in the first place. It also wouldn't change anything about how your class was being constructed, really, so why do it?
Take the following class as an example:
public class Test { }
Under the covers, because there is no declared constructor, the C# compiler implicitly adds a parameterless, public constructor to the class, allowing consumers to create an instance.
public class Program {
public static void Main() {
var test = new Test();
}
}
This is all fine and good if you want to be able to make instances of your class. The singleton pattern intends to only provide a single instance of a type to the consumers. We could add this static instance to our test type like so:
public class Test { public static Test Instance {get;} = new Test(); }
and we would be able to get this static instance like so:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // less than ideal
}
}
So we are providing access to our singleton object through it's instance field, as expected, but we can still create instances of the singleton type, which is less good, as it goes against the purpose of a singleton (namely, having only a single shared instance.)
So we add a private, parameterless constructor to the type.
public class Test {
private Test() {}
public static Test Instance {get;} = new Test();
}
Adding a constructor to a type will cause the C# compiler not to add an implicit public parameter-less constructor. Making it private allows it to be accessed within the class scope, which is used for instantiating our instance property, and prevents anything else from instantiating the object. The end result being:
public class Program {
public static void Main() {
var test = Test.Instance; // good
var other = new Test(); // Compile time error
}
}
Your singleton object now prevents other instances of the class from being instantiated, and the only way to use it is through the instance property as intended.
In simple terms, if you remove the private constructor, then anyone will be able to create a new instance of Singleton:
// With the private constructor, the compiler will prevent this code from working.
// Without it, the code becomes legal.
var newInstance = new Singleton();
And if anyone can instantiate Singleton as above, then you no longer have a singleton.
Another cleaner way to do it is to use readonly on you private instance.
This is less code and also thread safe. The CLR takes care of everything for you, no need for lock , check for null and stuff.
public sealed class Singleton
{
private static readonly Singleton _instance = new Singleton();
public static Singleton Instance {
get {
return _instance;
}
}
private Singleton()
{
}
}
Then simply test:
[TestMethod]
public void IsSingleton()
{
Assert.AreSame(Singleton.Instance, Singleton.Instance);
}
EDIT:
example using lock
public sealed class Singleton
{
private static readonly object _lock = new object();
private static Singleton instance = new Singleton();
public static Singleton Instance
{
get
{
lock(_lock)
{
if (instance==null)
{
instance = new Singleton();
}
return instance;
}
}
}
private Singleton()
{
}
}
In simplest terms, if you remove private, the default public constructor will get exposed. Then outsiders will be allowed to use new Singleton(); and make number of instances of Singleton class. So no Singleton Pattern will be there.
Additionally this classic implementation of Singleton pattern (private constructor + static getInstance() with either lazy-loading or eager loading) is so evil. In modern day you must switch to a Dependency-Injection framework instead.
This should work just fine. You could also make the class static and generic so you can store whatever kind of value in instance you want it to hold. This would facilitate the separation of concerns, keeping the singleton pattern and the class that it will contain separate.

Does an empty private constructor in a nested class make any sense?

I came across a source code with a nested class like this:
public class OuterClass
{
// code of the outer class
protected class NestedClass
{
private string myVar;
private NestedClass() {} // <--- empty private ctor
public NestedClass(string myVar)
{
this.myVar = myVar;
}
}
}
What could be the reason to create this empty private constructor?
I know when implementing a singleton the constructor must be private to prevent other classes to create an instance. However in the case the is another public constructor, so this cannot be the reason.
One reason I thought of would be to not allow the creation of an instance without a value for the variable, that is passed as parameter to the public constructor, but as far as I know this shouldn't be possible when the is simple no other constructor than the public constructor with parameter. Is that correct?
Edit: A answer that was deleted now, mentioned the default constructor. As far as I know a "hidden" default constructor only exists if there is no manually written constructor at all. This is described here:
These constructors are injected into all class declarations that do not introduce other constructors.
Therefore the empty constructor of my nested class, is not a default constructor, but simply a constructor without parameters. I assume that this is the case for top-level classes and nested classes alike.
If you have a non-default constructor and do not specify a default constructor, it will not be possible for any code to access the default constructor, because the compiler will not create one.
If you have a non-default constructor and also specify a private default constructor then it is possible for a NestedClass method to use the default constructor. Your code does not do this, so it is not necessary to provide a default constructor (private or otherwise).
There also an obscure case where it can make a difference: By providing the default NestedClass constructor, you enable reflection to access it.
The following program demonstrates.
If you run it, it will print "Demo.OuterClass+NestedClass".
If you comment-out the private default NestedClass constructor and run it, it will crash.
Other than this unlikely case, I can see no sensible reason to provide the private constructor.
using System;
using System.Reflection;
namespace Demo
{
public class OuterClass
{
protected class NestedClass
{
private string myVar;
private NestedClass(){} // Commenting-out this line will cause the reflection to break.
public NestedClass(string myVar)
{
this.myVar = myVar;
}
}
}
public class MyDerivedClass: OuterClass
{
public MyDerivedClass()
{
Type type = typeof(NestedClass);
var ctor = type.GetConstructor(BindingFlags.Instance|BindingFlags.NonPublic, null, Type.EmptyTypes, null);
var nested = (NestedClass) ctor.Invoke(null);
Console.WriteLine(nested);
}
}
public static class Program
{
private static void Main()
{
var test = new MyDerivedClass();
}
}
}
If you don't want to explicitly allow reflection to call the private default constructor, then I would say that there is indeed no point in providing it, and you should remove it from the code.
I think this means that only this class can create instances of itself using this constructor. Does the code in the class call this constructor anywhere?
Normally you'd have a private constructor if the class wanted to restrict you to calling some sort of factory method defined on it in order to create it, but as there's another constructor defined then this doesn't seem to be the case.
You can use reflection to locate the private constructor, and once you've got the ConstructorInfo for the private constructor you can invoke it in order to create an instance of the class, but this would be a very niche thing to do!

How to create a class without any constructor just like MessageBox class

How can i create a class with zero constructor, just like MessageBox class which has no constructor.
I can not make this class static, beacause a public static method is declared in it, and that method makes object of this class.
in C# 3.5
i want to make this class just like System.Windows.Forms.MessageBox class,
in which there is no constructor and
when we create object of this class error occurres :
this class has no constructor
where as a class with a private constructor when object creates error occurrs -
the constructor is not accessible due to its protection level.
The only way to create a class without a constructor is to use static class.
However, it seem you want to be able to create instances of this class from inside the class itself, which is not possible with a static class. For that, you should give the class a private constructor:
class Foo
{
private Foo() { }
public static Foo Create()
{
return new Foo(); // Only members of Foo can directly invoke the constructor.
}
}
If a method outside of Foo in the same assembly tries to instantiate Foo, the message given will be that the constructor is not accessible due to its protection level. If you try to access it from another assembly, it will give the message that Foo has no constructors.
The methods on MessageBox are static; you can do that with the static modifier:
public static class Foo {
public static void Bar() {...}
}
then:
Foo.Bar();
In earlier versions of c# (before static was allowed on classes) you had to cheat:
public class Foo {
private Foo() {} // hide the constructor
public static void Bar() {...}
}
Make it static class with no constructor or make it an Abstract class.
Make a static class, or make a class with a private constructor.
You can add public STATIC methods into your class and you would acheve the same as in messagebox.
Remember that static methods cannot access non static properties or methods in the same class.
Hope it helps.
Consider usage of Creational patterns, described in GOF ("Gang Of Four")
There are the following ways:
1) If you want to have only one instance of object to be created, use Singleton
There is a good example of thread-safe singleton on MSDN
In this strategy, the instance is created the first time any member of
the class is referenced
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
private Singleton(){}
public static Singleton Instance
{
get
{
return instance;
}
}
}
2) If you don't want to specify the exact class to create, use Factory method
Here is an extract from an article on C#-Corner Factory method Design pattern using C#
abstract class Factory
{
public abstract Product GetProduct(); //Factory Method Declaration
}
class concreteFactoryforProcuct1 : Factory
{
public override Product GetProduct() //Factory Method Implementation
{
return new Product1();
}
}
3) If there is a group of objects to be created this way, use Abstract factory
Here are extracts from an article on codeproject: Understanding and implementing abstract factory pattern in C#
Creating the Abstract Factory
interface IPhoneFactory //'I' stands for interface no relation with Iphone
{
ISmart GetSmart();
IDumb GetDumb();
}
Creating the Concrete Factories
class SamsungFactory : IPhoneFactory
{
public ISmart GetSmart()
{
return new GalaxyS2();
}
public IDumb GetDumb()
{
return new Primo();
}
}
...
Creating the Client
enum MANUFACTURERS
{
SAMSUNG,
HTC,
NOKIA
}
class PhoneTypeChecker
{
IPhoneFactory factory;
...
public PhoneTypeChecker(MANUFACTURERS m)
{
m_manufacturer= m;
}
public void CheckProducts()
{
switch (m_manufacturer)
{
case MANUFACTURERS.SAMSUNG:
factory = new SamsungFactory();
break;
case MANUFACTURERS.HTC:
factory = new HTCFactory();
break;
case MANUFACTURERS.NOKIA:
factory = new NokiaFactory();
break;
}
...
factory.GetSmart();
factory.GetDumb();
...
}
}
static void Main(string[] args)
{
PhoneTypeChecker checker = new PhoneTypeChecker(MANUFACTURERS.SAMSUNG);
checker.CheckProducts();
...
}
4) Use you common sense to develop your own design that would satisfy your needs.
If the purpose of it is not allowing user it instantiate new instances of the class you could make
all constructors less visible then public .
For example - protected.

Differences between static class and instance class with private constructor

Although a static class has only one instance and can't be instantiated, a class with a private constructor can't be instantiated (as the constructor can't be seen), so every time you call this class, this is the same one instance?
Factory classes always follow the last convention (instance class with private constructor). Why is this?
Thanks
There's nothing stopping the class with the private constructor from having a public static method which returns instances of the class:
public class NoPublicConstructor
{
private NoPublicConstructor()
{
}
public static NoPublicConstructor NewInstance()
{
return new NoPublicConstructor();
}
}
As you can see, the static method does not return the same one instance.
edit: One of the reasons factory classes do this is to be able to separate responsibility in future versions: while your code always calls the factory creation method, the author may move all the "guts" out of that class into a different one and your code won't need to know the difference. Calling that class' (public) constructor ties it to an extent to the original class implementation.
You can't* get an instance from outside the class, but you can from inside. A static method or an inner class can create and return an instance of the class with a private constructor. The static class cannot be instanced by anything.
class Foo
{
private Foo()
{
}
public class Bar
{
public Bar()
{
}
public Foo GetFoo()
{
return new Foo();
}
}
}
..
Foo.Bar fooBar = new Foo.Bar();
Foo foo = fooBar.GetFoo();
Edit: *I use the term "can't" loosely. Brian Rasmussen pointed out in the comments to the OP that another method to obtain an instance is through a call through System.Runtime.Serialization.FormatterServices, and this is external to the class itself.
Foo foo = (Foo)System.Runtime.Serialization.FormatterServices.GetSafeUninitializedObject(typeof(Foo));
Creating a class with private constructor is the common pattern for implementing a "Singleton" object.
The Singleton usually will instantiate an instance of itself, and only allow access to it through a static "Instance" property, which means there's only ever one instance of the class.
The advantage of using a Singleton over a purely static class is that you can utilize interfaces and different implementation classes within the singleton. Your "Singleton" might expose an interface for a set of methods, and you can choose which exact implementation class to instantiate under the covers. If you were using a purely static class, it would be hard to swap out a completely different implementation, without impacting other code.
The main downside of Singleton is that it's difficult to swap out the implementation class for testing, because it's controlled within the Singleton private methods, but there are ways to get around that.

Private constructor and public parameter constructor

I heard that a private constructor prevents object creation from the outside world.
When I have a code
public class Product
{
public string Name { get;set;}
public double Price {get;set;}
Product()
{
}
public Product(string _name,double _price)
{
}
}
Here I still can declare a public constructor (parameter), won't it spoil the purpose of the private constructor? When do we need both private and public constructor (parameter) in code?
I need a detailed explanation please.
The reason you would use the pattern you're describing is when you want to control how the object is instantiated.
In your example, for instance, you're saying the only way to create a Product is by specifying its name and price. This is with respect to the outside world, of course. You could also do something similar using other access modifiers, and it would have different implications, but it all boils down to controlling how you want the objects instantiated with respect to who will be doing it.
If you wanted to prevent object creation altogether you would have to make all your constructors private (or protected). That would force the object to be created from within itself (or an inherited class).
Also, as Matti pointed out in the comment below, when you define a constructor that is parameterized you don't need to specify a private default constructor. At that point it is implied.
Constructors can be chained together to avoid having to duplicate code. It is quite common to have private constructors, that nobody is supposed to call outside of the class, that are chained from a public constructor.
Example:
public class Test
{
private Test(int? a,string b) { }
public Test(int a) : this(a, null) { }
public Test(string b) : this(null, b) { }
}
Here there are two public constructors, one taking a string and one taking an int. They both chain to the common private constructor that takes both arguments.
Also, you can construct new objects from within the same class by using the private constructor. For instance, when you want specialized constructors only available through static factory methods:
public static Test Create()
{
int? a = ReadConfigurationForA();
string b = ReadConfigurationForB();
return new Test(a, b);
}
When it is not be a good idea to expose a private constructor to the outside world, add a static factory method that fetches the correct arguments to pass on the constructor.
You need a private constructor when you only want that constructor to be called from within the class itself. In your example you are forcing the calling object to provide 2 parameters when creating the object.
With a private constructor you could do something like:
public static GetInstance ()
{
return new YourObject();
}
but nothing else except the object could call the parameterless constructor.
It's commonly used to create a singleton pattern:
http://www.dofactory.com/Patterns/PatternSingleton.aspx
You would use a constructor with parameters when you wanted to force calling code to pass a value to the constructor in order to create an instance of your class. In your example, calling code must use the parameter version of the constructor in order to create a Product.
A private constructor is a special instance constructor. It is commonly used in classes that contain static members only. If a class has one or more private constructors and no public constructors, then other classes (except nested classes) are not allowed to create instances of this class.
For more details refer to this:
http://msdn.microsoft.com/en-us/library/kcfb85a6(VS.80).aspx

Categories

Resources