Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy can't I define a default constructor for a struct in .NET?
    text
    copied!<p>In .NET, a value type (C# <code>struct</code>) can't have a constructor with no parameters. According to <a href="https://stackoverflow.com/questions/203695/structure-vs-class-in-c#204009">this post</a> this is mandated by the CLI specification. What happens is that for every value-type a default constructor is created (by the compiler?) which initialized all members to zero (or <code>null</code>).</p> <p>Why is it disallowed to define such a default constructor?</p> <p>One trivial use is for rational numbers:</p> <pre><code>public struct Rational { private long numerator; private long denominator; public Rational(long num, long denom) { /* Todo: Find GCD etc. */ } public Rational(long num) { numerator = num; denominator = 1; } public Rational() // This is not allowed { numerator = 0; denominator = 1; } } </code></pre> <p>Using current version of C#, a default Rational is <code>0/0</code> which is not so cool.</p> <p><strong>PS</strong>: Will default parameters help solve this for C#&nbsp;4.0 or will the CLR-defined default constructor be called?</p> <hr> <p><a href="https://stackoverflow.com/questions/333829/why-cant-i-define-a-default-constructor-for-a-struct-in-net#333840">Jon Skeet</a> answered:</p> <blockquote> <p>To use your example, what would you want to happen when someone did:</p> <pre><code> Rational[] fractions = new Rational[1000]; </code></pre> <p>Should it run through your constructor 1000 times?</p> </blockquote> <p>Sure it should, that's why I wrote the default constructor in the first place. The CLR should use the <em>default zeroing</em> constructor when no explicit default constructor is defined; that way you only pay for what you use. Then if I want a container of 1000 non-default <code>Rational</code>s (and want to optimize away the 1000 constructions) I will use a <code>List&lt;Rational&gt;</code> rather than an array.</p> <p>This reason, in my mind, is not strong enough to prevent definition of a default constructor.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload