Click here to Skip to main content
15,885,925 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
C#
When do we need both private and public constructor in a class? Please explain 


What I have tried:

When do we need both private and public constructor in a class
Posted
Updated 3-May-16 20:46pm
Comments
Sergey Alexandrovich Kryukov 3-May-16 16:19pm    
What is that? Test question, interview question? As if they tried hard to tech people thinking in perverted way...
This is simply an incorrect question. What would it mean, "when"? Whenever the developers needs it. There is no a finite set of predefined cases or cookbook recipes.

When you do development, you don't pose such pointless questions. When you need a private constructor, you add one, when you need public, you add one. I'll tell you more: when you need an internal constructor, you also add one.

—SA
BillWoodruff 4-May-16 1:55am    
Try to make your question more specific.

First, read this: [^] and be aware that a non-static Class defined without a constructor has a default constructor created for it. Then, read this: [^].

Second, burn into your brain that if you define a constructor with any non-optional parameter i.e., any parameter that does not have its default value set in the parameter list, that a default parameterless constructor is not created.

Try this code in a Visual Studio Project:
C#
public class MyNoConstructorClass
{
    public string WhoAmI { set; get; }
}

public class MyOneParameterConstructorClass
{
    public string WhoAmI { set; get; }

    public MyOneParameterConstructorClass(string whoami = "nobody")
    {
        WhoAmI = whoami;
    }
}

public class MyTwoParameterConstructorClass
{
    public string WhoAmI { set; get; }

    public string WhatAmI { set; get; }

    public MyTwoParameterConstructorClass(string whatami, string whoami = "nobody")
    {
        WhatAmI = whatami;
        WhoAmI = whoami;
    }
}
Yes, you will get a compile error: comment out the line where compile fails, and, then:

Test it like this in some method or EventHandler: put a break-point before the first call that creates an instance of 'MyNoConstructor, and then single-step (F11 in Visual Studio) through the code observing what happens:
MyNoConstructorClass mnc = new MyNoConstructorClass();
            mnc.WhoAmI = "look, ma, no constructor !";

MyOneParameterConstructorClass moc = new MyOneParameterConstructorClass();
            moc.WhoAmI = "somebody with a default parameter defined";

MyTwoParameterConstructorClass m2c = new MyTwoParameterConstructorClass("one");

MyTwoParameterConstructorClass m2c2 = new MyTwoParameterConstructorClass(whatami: "weird");

MyTwoParameterConstructorClass m2c3 = new MyTwoParameterConstructorClass(whoami: "weird");
In general:

1. non-static classes will always have a 'public access point that results in an instance of the class being created ... how else would you create one if they didn't ? keep in mind that, as described above, a parameterless constructor is created by default if you haven't created one given the parameter list syntax is valid.

1.a. the circumstances in which a non-static class requires a parameterless constructor vary.

1.b. in cases where the compiler demands you have a public parameterless constructor, you can often avoid writing one by using the 'base() directive preceded by a colon at the end of your constructor with parameters.

1.b.1. serialization is one example of when the compiler may demand a parameterless constructor. what happens, specifically, may vary with the serializer you use (XML, JSON, DataContract). I have read that some serializers can work with a parameterless constructor declared as 'private. I've never written code to test that, and don't intend to :) Marc Gravell (StackOverFlow guru) has stated that the DataContract serializer does not require a parameterless constructor.

1.b.1.a. 'dependency injection' by some external agency may also be a case where a parameterless constructor must be present.

1.b.2. in general, one might say that a parameterless public ctor on a non-static class is required when some external entity, or some usage, expects/demands it to have one.

2. static classes have an optional static constructor which cannot be declared 'public. it will be automatically invoked when any reference is made to the 'static class or its members.

3. the case of a non-static class which uses a constructor whose access-type is defined as 'private, and uses a public static variable to hold the one-and-only instance of the class is called a Singleton.

4. the initialization of 'Struct objects has its own characteristics, and you should read the documentation about that.
 
Share this answer
 
v2
The question is not correct and cannot be answered. Formally speaking, I already explained all you need to know about the subject in my comment to the question. Of course, you should also know how constructors work and all the access modifiers and their purposes. You can read it in the appropriate part of the reference: Redirect Notice[^].

Now, this understanding should be applied to all the members of a class or a struct, not just to constructors. There is absolutely no difference.

The other step requires some logic. If the type is static, you may or my not need any constructors, but a static constructor can be required and, naturally, an instance constructor could not possibly be allowed, because there are no instances. Apparently, such constructor will be always private, because it is never called explicitly, but is called before any member of the type is first used.

With a non-static type, there all the options. It depends on usage. A constructor is needed when you create an instance, so, if you use the type in the same assembly, an instance can be created with internal constructor. A public one is needed when you need to create an instance in some other assembly. Note that you may not need any constructors at all, because a default constructor is used (read about them). You may need no non-private constructors because you can have a static factory method which returns the instance of the same class. The implementation of this method can use a private constructor. Also, a static (and hence private) constructor can be used to initialize some static members. And you can use a private constructor in the implementation of the internal or public constructor. Anyway, you can face many different combinations of needs. So, you have to act as I described in my comment to the question.

Disclaimer: this is not the answer to the question. The question is incorrect; it cannot and should not be answered. This is just the explanation of what one needs to know on the subject.

—SA
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900