Static Class VS Private Constructor
Asked Answered
F

5

12

Today, I have been reading about static class and private constructor.

Static Class - We cannot create an instance on the static class. we cannot inherit the static class. Only single instance is generated.

Private Constructor - We cannot create an instance. We cannot inherit. (I Don't know about how many instance is generated.)

I created two console application i.e. One for static Class, One for Private constructor.

Static Class Code

enter image description here

I understood single object in generated as constructor is called once.

Private Constructor Code

enter image description here

Now, I didn't understand that whether any object is generated or not.

I have two question.

Question 1. I didn't find any particular difference between Private constructor and Static class. Can you please suggest me that in which scenario where I should use Private Constructor and where should I use Static class as I can use both of them.

Question 2. If I use private constructor, how many objects is generated?

Thanks.

EDIT :

I think that people didn't understand my question. I know that static constructor always call once on the first reference. Static constructor is used to initialize static members of the class.

Question 1. I have a situation : I need to create a class which cannot be instantiated.I can do this by either static class or private constructor. So my question is that "Is there any difference between both of them? which one I should use??"

Question 2. If I use private constructor, how many object is created? If answer is 0 then how private constructor's memory allocation works in the CLR. There is no memory allocation if I use private constructor.

Furious answered 23/6, 2016 at 11:10 Comment(6)
Private Constructor - We cannot create an instance.isn't right. Nested classes canDeedradeeds
In short: The difference is basically that a static class prevents any instantiation while a private constructor only prevents outside instantiation. A private constructor makes sense if you want to implement the singleton pattner. So only a single object of you class.Deedradeeds
your misinformed private constructors can be called, just only from inside that class, ie via another constructor or static method, a static constructor is called on first use of a class to initialise it it doesn't create an instanceThereunder
note for future reference you should never user images to upload written data, use the formatters code function for code and images for actual images, same goes for error messages copy the text not a image. images are not searchable or copy paste usable to create working copes of your codeThereunder
Okay MikeT. I will take care of it in the future post.Furious
There is the difference that testPrivateConstructor can have instances in principle, and values can have type testPrivateConstructor. For example you can make a variable testPrivateConstructor value = null;, or you can make a method parameter static void Consume(testPrivateConstructor value) { Console.WriteLine("The value was: " + value); }. Those things are disallowed for static classes like testStaticClass. And of course testPrivateConstructor can have members (methods, properties, fields, events) that are non-static.Stan
T
6

Both of you examples you are calling static methods the difference between the two is that the first method is being called within a static class which cannot be instantiated. The second class could be instantiated however you did not choose to.

The static constructor in the first example is run automatically at runtime when it is needed, it is generally only run once.

The private constructor is never run as you never instantiated a testPrivateConstructor object. not because it is private.

The Edit:

Q1: If you need a class that cannot be instantiated use a static class. Only use a private constructor instead of a static class if you need to initialise static members (or a singleton pattern).

Q2: If you use a private constructor you can instantiate an instance of your class within the class itself so the number of objects that are created depend on how many times you instantiate new objects.

Tinstone answered 23/6, 2016 at 11:22 Comment(3)
you just explained my code. Yes I know above things. But i want to know some different things. I know that I didn't choose. Please read my questions again. Thanks for the replyFurious
Sorry that you don't feel I answered your questions, your first question is difficult to answer because I don't agree with the premise 'I didn't find any particular difference between Private constructor and Static class' - they are not even similar in function (I have tried to explain why) The second question is comparable to asking: 'how long is a piece of string' - the constructor doesn't define how many objects are created.Tinstone
@Mohit this answer is correct, the issue is that you've misunderstood a little of what you have read, because of that your have mixed up a couple of points which is causing your confusionThereunder
T
2

your mixing up a few different things here

a static class public static class MyClass can only contain static elements and never be initialised

a constructor (whether public or private) always creates in instance of the class the public or private only says the visibility of the constructor.

this is commonly used when implementing a singleton design

private MyClass()
{
}
private static MyClass _Singleton;
public static MyClass Singleton
{
    get
    {
        if(_Singleton==null) _Singleton = new MyClass();
        return _Singleton
    }
}

}

the other is a Class Initialiser, this is a little confusing because its syntax is very similar to a constructor baring the adding of a static keyword and lack of parameters

static MyClass()
{
    //configure static variables on first us only
    b = //read value from file or other resource not avalable at compile time
    a = b.Lenth; //can't be be done in class body as b would not have been initialised yet
}
private static int a;
private static string b;

ergo if your class can't be instantiated then you can only declare is as static nothing else will do that,

if you call a private constructor then every call creates an instance

a class initialiser can never be called its fired automatically on the first use of a class and does not create an instance

EDIT: here is a revised version of your test program

public static class StaticClassExample
{
    public static void ClassFunction()
    {
        Console.WriteList("This is a class function")
    }
}
public static class InitialisedStaticClassExample
{
    static InitialisedStaticClassExample()
    {
        Console.WriteList("This class has been initialised")
    }
    public static void ClassFunction()
    {
        Console.WriteList("This is a class function")
    }
}
public class PrivateConstuctorClassExample
{
    static PrivateConstuctorClassExample()
    {
        Console.WriteList("This class has been initialised")
    }
    private PrivateConstuctorClassExample()
    {
        Console.WriteList("This class has been Instantiated")
    }
    public static void ClassFunction()
    {
        Console.WriteList("This is a class function");
        var instance = new PrivateConstuctorClassExample();
        instance.InstanceFunction();
    }
    public void InstanceFunction()
    {
        Console.WriteList("This is a instance function")
    }
}
Thereunder answered 23/6, 2016 at 12:13 Comment(0)
M
1
  • Static constructor will be called first time when the class is referenced. Static constructor is used to initialize static members of the class.
  • In the non static class the private or public constructor will not be called. Static members will not be initialized either by private or public constructor.

    see the below exmaple

        class Program
        {
            static void Main(string[] args)
            {
                OnlyOne.SetMyName("I m the only one."); //static constructor will be called first time when the class will be referenced.
                Console.WriteLine(OnlyOne.GetMyName());
    
                NoInstance.SetMyName("I have private constructor"); //No constructor will be called when the class will be referenced.
                Console.WriteLine(NoInstance.GetMyName());
    
                Console.Read();
            }
        }
    
        static class OnlyOne
        {
            static string name;
            /// <summary>
            /// This will be called first time when even the class will be referenced.
            /// </summary>
            static OnlyOne()
            {
                name = string.Empty;
                Console.WriteLine("Static constructor is called");
            }
    
            public static string GetMyName()
            {
                return name;
            }
    
            public static void SetMyName(string newName)
            {
                name = newName;
            }
        }
    
        public class NoInstance
        {
            static string name;
            private NoInstance()
            {
                name = string.Empty;
                Console.WriteLine("No instance private constructor is called");
            }
    
            public static string GetMyName()
            {
                return name;
            }
    
            public static void SetMyName(string newName)
            {
                name = newName;
            }
        }
    }
    
Miramirabeau answered 23/6, 2016 at 11:17 Comment(0)
N
0

Question 2: 0

Question 1: you created a static class with a static constructor, but you do not need the instance in your case, since the method is static too and the only thing you need to run a static method is the class definition - no instance.

your second class works also without construction of an instance - the static method does not need one. and since this is a private constructor only class methods could create the instance. you would use the private constructor only in case of the singleton pattern i guess - without a local caller for private constructor it is rather useless.

Nahama answered 23/6, 2016 at 11:25 Comment(0)
A
0

Constructor of a class is called upon creation of instance of the class. Static constructors are called on initialization of the class. Read this

In example 1, your static constructor is initialized the as you are accessing a static method of the class. This is relevant for a static or non-static class.

In example 2, your private constructor isn't static. Your constructor wasn't called as there was no instance created. It has to be called by creating an instance of the class.

Private constructors are used to control the construction and destruction of the instance of the class. Since, only the class can call its constructor in this case. You need a static method to get the instance of the class

For example,

public class TestPrivateConstructor
{

private TestPrivateConstructor()
{
  Console.WriteLine("Instance is created, Private Constructor called");
}

static TestPrivateConstructor _instance;

public static TestPrivateConstructor GetInstance()
{
    if(_instance == null)
    {
       _instance = new TestPrivateConstructor();
    }
    return _instance;
}

public static void DisposeInstance()
{
   if(_instance !=null)
   {
      _instance.Dispose();
      _instance = null;
   }
}
public void TestMethod()
{
  Console.WriteLine("Test MEthod Called");
}
void Dispose()
{
 //Do something
}
}

For the code above, try using this. Now your private constructor is called as you created an instance.

class Program
{
   public static void Main(string[] args)
   {
     //Private constructor
     TestPrivateConstructor.GetInstance()
   }
}

Using the approach above, you can control the construction and destruction of the object. If you still have any questions, please feel free to ask.

Acquirement answered 23/6, 2016 at 11:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.