Can any one Explain that
(a) when we should use static class, static constructor and private constructor in our project.
(b) what is difference between static class and private constructor, static constructor and private constructor.
If possible please explain with relating to live example(with code) because there is so many confusing example of this.
Jaganathan BantheswaranPosted Dec 31, 2013, 6:00 AM
Static classes are not to be instantiated. You can access the methods & properties without creating an object of it by making the class & their properties & methods are static.
Use case: A class to have utility methods can be made as static
2. Static Constructor:
Static Constructors are invoked only once to initialize the static fields & properties when any member of the class is referenced or instance is created.
Use case: Reading required configuration data into static readonly fields, etc.
3. Private Constructor:
Private Constructor cant be invoked outside.
Use case: To create a singleton class.
Example:
Static class
static class Utils
{
// can be accessed like Utils.SayHello();
public static string SayHello()
{
}
}
Static Constructor
static class Utils
{
static string helloString;
// invoked when the SayHello is called.
static Utils()
{
helloString = "something";
}
// can be accessed like Utils.SayHello();
public static string SayHello()
{
return helloString;
}
}
Private Constructor:
class Singleton
{
// Not accessible out side
private Singleton() { }
// But inside ti create singleton class
private static Singleton singletonInstance = new Singleton();
public static Singleton GetInstance() { return singletonInstance ; }
}
Biswa Pujarini MohapatraPosted Dec 31, 2013, 5:24 AM
Static class :
1. Static classes are "self-documenting" code. Users of your library will know that this class should not be instantiated
2 All the fields/members should be static
public static class Foo
{ static int age=0;}
Private constructor
1 class can't be instantiated
2 need to declare an property or method to instantiate the class, this can enforce singleton design, class need to be declare as sealed
4 The private constructor simply makes it impossible for external code to instantiate the class freely without using reflection
public sealed class Test
{
public static readonly Test Instance = new Test(); // Singleton pattern
public int A; // Instance field
private Test() // This is the private constructor
{
this.A = 5;
}
}