TypeName | SA1129DoNotUseDefaultValueTypeConstructor |
CheckId | SA1129 |
Category | Readability Rules |
📝 This rule is new for StyleCop Analyzers, and was not present in StyleCop Classic.
A value type was constructed using the syntax new T()
.
A violation of this rule occurs when a value type T
is constructed using the syntax new T()
. To create a default
instance of a value type, use the equivalent syntax default(T)
instead.
For example, the following code would produce a violation of this rule:
ImmutableArray<int> array = new ImmutableArray<int>();
While the above appears to create a new immutable array which is ready to use, in reality the variable array
was
assigned a default instance of ImmutableArray<int>
, and almost any attempt to use the variable will result in a
NullReferenceException
. To avoid confusion with the behavior of reference types, default instances of value types
should always be created using the syntax default(T)
instead.
📝 This proposal only refers to the distinction between
default(T)
andnew T()
. Other default values, includingCancellationToken.None
,0
,0.0f
,IntPtr.Zero
, andRegexOptions.None
, would not produce a warning.
To fix a violation of this rule, replace the syntax new T()
with the equivalent syntax default(T)
.
#pragma warning disable SA1129 // Do not use default value type constructor
IntPtr zero = new IntPtr();
#pragma warning restore SA1129 // Do not use default value type constructor