| 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).
For native-sized integers constructed with new nint()/new nuint(), the code fix will only use
IntPtr.Zero/UIntPtr.Zero in projects where this has the same meaning, specifically, C# 11 with
runtime support for native-sized integers (e.g. .NET 7 or later). Otherwise, the code fix will use
default(nint)/default(nuint) to ensure identical behavior to the original code.
#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