Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why i cannot call the default constructor while having a private constructor?

Tags:

c#

i have the following class with a private overloaded constructor

 class Car
    {
        string _Make;
        string _Model;

        Car(string make, string model)
        {
            _Make = make;
            _Model = model;
        }
    }

then i've tried to call the default constructor of the above class

class Daytona
{
    public int Foo()
    {
        Car c = new Car(); //COMPILATION ERROR

        return 0;
    }
}

Note both classes are in the same namespace!

i could not create an instance of the Car using its default constructor. But either i create a default constructor or not i should be able to access the default constructor. but i why this error occurred?

okay fellows, something bad happened with VS 2010, when i restarted my machine VS 2010 compiled the above code. so that problem was solved.

its my compiler, when i recompiled it, again brought the error, in line " Car c = new Car();" error was MyNamespace.Car.Car(string, string) is inaccessible due to its protection level

But i want to drag this top to a new area, why would someone want to create a private constructor? (the above code just for testing!)

like image 625
Phill Greggan Avatar asked Sep 12 '26 13:09

Phill Greggan


2 Answers

public class Car
    {
        string _Make;
        string _Model;

        public Car(){}    

        public Car(string make, string model)
        {
            _Make = make;
            _Model = model;
        }
    }

Make it public instead, but you also need to add a parameterless constructor if you want to call it without parameters. The default constructor is no longer implicitly defined if you define another constructor (with parameters)

like image 194
TGH Avatar answered Sep 14 '26 01:09

TGH


You do not have a public constructor of class Car that does not require arguments to be passed. Therefore you need to add this constructor. This constructor has to be explicitly defined when you've already defined another constructor. I also added public to the constructor you already had.

public class Car
{
    string _Make;
    string _Model;

    public Car()
    {
        // Default constructor - does not require arguments
    }

    public Car(string make, string model)
    {
        _Make = make;
        _Model = model;
    }
}

The second constructor can still be private if you prefer, but you won't be able to call it directly.

Now you can do either:

Car A = new Car(); // Creates a new instance, does not set anything
Car B = new Car("MyMake", "MyModel"); // Creates a new instance, sets make and model
like image 34
grovesNL Avatar answered Sep 14 '26 01:09

grovesNL