Click here to Skip to main content
15,886,806 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I know that the C# compiler will put a default no-args constructor for instance types but what happens if the class is static? Is the case the same?

What I have tried:

Looking at the Programming Guide on C# for static constructors but didn't find anything related to my question.
Posted
Updated 9-Mar-18 2:13am
Comments
PIEBALDconsult 9-Mar-18 8:14am    
No, pretty sure not, judging by what Jon Skeet says.
http://csharpindepth.com/Articles/General/BeforeFieldInit.aspx

1 solution

Looking at the IL, the only time a static constructor will be generated for you is if you have static field / property initializers.
C#
// No static ctor:
public static class A { }

// Generated static ctor:
public static class B
{
    static int answer = 42;
}

// Generated static ctor:
public static class C
{
    public static int Answer { get; } = 42;
}

// Explicit static ctor:
public static class D
{
    static D()
    {
    }
}

If there are no field or property initializers, and no explicit static constructor, then there's no need for a static constructor.

Static Constructors (C# Programming Guide) | Microsoft Docs[^]
 
Share this answer
 
Comments
The_Unknown_Member 9-Mar-18 10:17am    
Are values of fields and properties set to their defaults within the constructor?
Richard Deeming 9-Mar-18 10:20am    
No; the CLR zeros out the memory of any new object, so they're set to the defaults automatically, without needing a constructor.

However, if you don't set the field anywhere, you will probably get a compiler warning.
Ehsan Sajjad 9-Mar-18 14:09pm    
good explained, 5ed

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900