When you try to return from the method return new Size();
the error Do not use default value type constructor
crashes and offers to replace the string with return default(Size);
. No matter how difficult it is to use default(T)
, I just want to understand what's the difference?
2 answers
Here is a related discussion: https://github.com/DotNetAnalyzers/StyleCopAnalyzers/issues/1482 .
The fact is that for structures, overriding the default constructor is currently not allowed. Structures always have an initial value (initialized with zeros), which can be a “bad”, incorrect value. For example, CancellationToken
: its initial value is the same as CancellationToken.None
.
If you use the syntax with new
, it looks as if you are creating a good, usable like all other values. The syntax with default
allows you to emphasize that this is a special uninitialized value.
Note that this is not a compilation error, but a warning of the style analyzer. You can completely disable it in the settings, it only affects the readability of the code.
Note that if constructors without parameters are resolved, the difference between new T()
and default(T)
will become more serious: default(T)
will mean an uninitialized, zero-written value, and the constructor will be able to perform additional initialization.
- well or so :-) somehow a more holistic explanation came out :) - Grundy
- By the way, since this is an analyzer rule, can it be disabled? - Grundy
- :-D responded to the comment before I sent it :-D - Grundy
- @Grundy: Well, yes, you can disable. Just added exactly this. - VladD
- one@Lightness: It’s somewhere in your settings you’ve got to read analyzer warnings as errors. Must be customized. - VladD
This statement is needed to get the default value.
- null - for reference types
- 0 or structure for value types.
In MSVS 2013, everything works without warning.
Apparently , this rule has been added to the code analyzers of new studios .
In principle, it looks quite reasonable, given that structures cannot have a constructor without parameters.
And since the result of the default(Size)
and new Size()
calls is exactly the same, the default
call may seem more logical.
The primary purpose of existence of
default(T)
is templates. In the template, the programmer does not know whetherT
anull
value, and whether there is a constructor without parameters. Butdefault(T)
is always there.
- It makes sense to say that the primary purpose of the existence of
default(T)
is templates. In the template, the programmer does not know whetherT
anull
value, and whether there is a constructor without parameters. Butdefault(T)
is always there. - VladD - @VladD, added a comment in response :) - Grundy
Size
class, and apparently resharper swears - GrundySize
fromSystem.Windows
. Resharper disconnected, the problem is the same. - LightnessVS Enterprise 2015 Update3
- Lightness