user3589535
user3589535

Reputation:

Access specifier for constructors in C#

Can I have constructors with same parameter list but one private and one public or any other access specifier in C#. Thanks in advance.

Upvotes: 0

Views: 1304

Answers (5)

Rik
Rik

Reputation: 29243

No, you can't.

You can create a private constructor and any number of static methods (with whatever access modifiers you prefer) which return an instantiated object.

public class MyClass
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }

    private MyClass() {}

    public static MyClass InstanceWithProp1(string prop1)
    {
        return new MyClass() {Prop1 = prop1};
    }

    public static MyClass InstanceWithProp2(string prop2)
    {
        return new MyClass() {Prop2 = prop2};
    }
}

Upvotes: 0

Peter Ritchie
Peter Ritchie

Reputation: 35869

What I generally do in this circumstance is have a private "initializer" constructor that one or more other constructors invoke. This, of course, demands that you have a different parameter list. For example (very pedantic):

    private Person ( String firstName, int age )
    {
        this.firstName = firstName;
        this.age = age;
    }

    public Person ( String firstName, String lastName, int age )
        :this(firstName, age)
    {
        this.lastName = lastName;
    }

This takes advantages of constructor chaining to do something I call accumulative construction.

Although this example has a private constructor, it's pedantic and you probably would not have a need for it in this particular example--it's just to show the concept.

Upvotes: 0

A constructor can be looked at as a special method. The constructor is called implicitly by the framework when an instance is created. but the overloading criteria for both methods and constructors are the same.

You cannot overload by return type or access modifiers in C#.

You can only do so by having different type of parameters or different number of parameters which also can be called as the method signature.

From MSDN http://msdn.microsoft.com/en-us/library/aa268049%28v=vs.60%29.aspx:

8.6.6 Constructor Overloading

Overloading of constructors is identical in behavior to overloading of methods. The overloading is resolved at compile time by each class instance creation expression (§15.8).

Upvotes: 0

D Stanley
D Stanley

Reputation: 152626

Can I have constructors with same parameter list but one private and one public or any other access specifier in C#.

No - the access is not part of the method signature, so that would be a collision. Think about it, how would the compiler know whether to bind to the public or private constructor?

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1502546

No, you can't overload either constructors or methods by just varying access modifiers (or return types in the case of methods). You can only overload members if they have different signatures.

Upvotes: 4

Related Questions