20

How is it possible that class in C# may has no constructors defined? For instance I have a class

internal class TextStyle
{
    internal string text = "";
    internal Font font = new Font("Arial", 8);
    internal Color color = Color.Black;
}

And in the code this class is instantiated as

TextStyle textParameters = new TextStyle();
Heinzi
  • 167,459
  • 57
  • 363
  • 519
TOP KEK
  • 2,593
  • 5
  • 36
  • 62

1 Answers1

51

If you don't declare any constructors for a non-static class, the compiler provides a public (or protected for abstract classes) parameterless constructor for you. Your class effectively has a constructor of:

public TextStyle()
{
}

This is described in section 10.11.4 of the C# 4 spec:

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract, then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public.

The only classes in C# which don't have any instance constructors are static classes, and they can't have constructors.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • I'm writing a unit test that requires a [`BlobDownloadInfo`](https://learn.microsoft.com/en-us/dotnet/api/azure.storage.blobs.models.blobdownloadinfo?view=azure-dotnet) instance. Despite this class seemingly having no constructor, i.e. you'd expect `new BlobDownloadInfo()` to work, the compiler is complaining `'BlobDownloadInfo' does not contain a constructor that takes 0 arguments`. So I'm guessing something (somewhere) has changed since this answer was written..... – Liam Sep 21 '20 at 10:39
  • Seems this class can somehow (voodoo?) only be [generated using a factory](https://github.com/Azure/azure-sdk-for-net/blob/e002645ffbe4669e0a4315fb93348465fdff5d96/sdk/storage/Azure.Storage.Blobs/tests/UnitTests.cs) – Liam Sep 21 '20 at 10:39
  • 2
    @Liam: I can't easily find the source to that class (via a two minute search...) but I'd expect it to have a constructor - just not a publicly accessible one. If it didn't have any constructors declared in the source code, I'd expect to see the parameterless one generated by the constructor to be documented (presumably without any text, just its presence being noted). Nothing has changed in the *language* here. – Jon Skeet Sep 21 '20 at 11:09
  • 4
    @Liam: Now found the source code, and as expected, there's an internal constructor: https://github.com/Azure/azure-sdk-for-net/blob/548336e6537d87ee9c1a179b7677620dddf13225/sdk/storage/Azure.Storage.Blobs/src/Models/BlobInfo.cs#L79 – Jon Skeet Sep 21 '20 at 11:10