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

Case 1:

I'm trying this

MessageBox m = new MessageBox(); 

And got a compilation error

'System.Windows.Forms.MessageBox' does not contain constructors

Case 2:
Then I created a class without a constructor

 class myClass { } 

and tried myClass my = new myClass(); This time I did not find an error.

Now, my question is:

  • Why am I getting an error in the first case?

Since both classes and each class have a default constructor, then

  • Where is the default constructor in the first case?
+6
constructor c #
source share
5 answers

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

Archil is also right. If an explicit constructor is specified, an implicit default constructor is no longer created.

And regarding x0ns comments: Yes, it is also impossible to create static classes. Do not use static classes, this is a bad design (there are exceptions).

+15
source share

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

+5
source share

MessageBox is intended to be used as a static class - see http://msdn.microsoft.com/en-us/library/79b3xss3(VS.80).aspx

You can make your static stat using:

 static class myclass {} 
+3
source share

System.Windows.Forms.MessageBox does not have a default constructor (empty).

The constructor can be hidden by setting its accessibility to something other than public.

The construction of the class declares that you cannot use it as an object.
It has only static methods that can be used without instantiating an object of this class.

+1
source share

In case 1, the MessageBox is a static class, it has no constructors (update - it has a private constructor reflecting a reflector, but the OP gave an incorrect compiler error message). Static classes are defined as follows:

 public static class MessageBox { } 

A static class can only have static methods and as such should not be created.

In case 2, MyClass is not a static class, and the compiler generates a default constructor for you if you do not define any constructors.

UPDATE: for all downvoters: compile the project with a static class and examine it in the reflector - it decompiles without a static keyword, because for a static class there is no MSIL or metadata; the compiler (in .net 2.0 or later) generates an abstract private class without constructors. The keyword "static" is just syntactic sugar. Also, in 1.0 / 1.1 of .NET (when the MessageBox was created), the static keyword did not exist for classes, and the closed / closed ctor was the accepted pattern.

-2
source share

All Articles