Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't the MessageBox class have a default constructor in C#?

Case 1:

I am trying this

MessageBox m = new MessageBox();

And got compilation error

'System.Windows.Forms.MessageBox' has no constructors defined

Case 2:
Then, I have made a class without constructor

class myClass
{

}

and tried myClass my = new myClass(); This time I found no error.

Now, my question:

  • Why I am getting error in 1st case?

Since, both are classes and every class have default constructor, then

  • Where is default constructor in 1st case?
like image 362
Javed Akram Avatar asked Apr 02 '11 15:04

Javed Akram


People also ask

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members. A constructor of a class A is trivial if all the following are true: It is implicitly defined. A has no virtual functions and no virtual base classes.

Does every class have a default constructor C#?

In c#, if we create a constructor without any parameters, we will call it a default constructor. Every instance of the class will be initialized without any parameter values. Following is the example of defining the default constructor in the c# programming language.

What happens if there is no default constructor?

A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .

Why can struct have Parameterless constructor?

Although the CLR allows it, C# does not allow structs to have a default parameter less constructor. The reason is that, for a value type, compilers by default neither generate a default constructor, nor do they generate a call to the default constructor.


2 Answers

The constructor may be private or protected in order to forbid direct instantiation. Use the static factory method instead. There is a static method Show in the MessageBox class.

Archil is right, too. If theres a explicit constructor defined, the implicit default constructor is not created anymore.

And regarding x0ns comments: Yes, it's also impossible to instantiate static classes. Don't use static classes, thats poor design (there are exceptions).

like image 121
atamanroman Avatar answered Oct 01 '22 03:10

atamanroman


In c#, evey class automatically has default constructor if NONE is defined. MessageBox defines other constructors, so it does not automatically have default constructor

like image 25
archil Avatar answered Oct 01 '22 04:10

archil