From 83c71d9aa59268cf488a769b72ca2298148c8794 Mon Sep 17 00:00:00 2001 From: Owen Smith Date: Thu, 10 Sep 2026 08:34:59 -0400 Subject: [PATCH] PatternString: treat null values as non-passing Currently crashes. Maybe we consider adding an AllowNulls to the attribute --- .../PatternStringAttributeAnalyzer.cs | 2 +- .../Specs/PatternStringAttributeAnalyzer.cs | 9 +++++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/Rules/D2L.CodeStyle.Analyzers.Rule.PatternString/PatternStringAttributeAnalyzer.cs b/src/Rules/D2L.CodeStyle.Analyzers.Rule.PatternString/PatternStringAttributeAnalyzer.cs index 80f45863..c1439dc6 100644 --- a/src/Rules/D2L.CodeStyle.Analyzers.Rule.PatternString/PatternStringAttributeAnalyzer.cs +++ b/src/Rules/D2L.CodeStyle.Analyzers.Rule.PatternString/PatternStringAttributeAnalyzer.cs @@ -249,7 +249,7 @@ ConcurrentDictionary> regexCache // [PatternString] requires the assigned value to be a compile-time // constant so that we can evaluate it here. Optional constant = valueOperation.ConstantValue; - if( !constant.HasValue ) { + if( !constant.HasValue || constant.Value is null ) { context.ReportDiagnostic( Diagnostic.Create( descriptor: Diagnostics.PatternStringMustBeConstant, diff --git a/tests/D2L.CodeStyle.Analyzers.Test/Specs/PatternStringAttributeAnalyzer.cs b/tests/D2L.CodeStyle.Analyzers.Test/Specs/PatternStringAttributeAnalyzer.cs index c13ac2c5..c4cd295b 100644 --- a/tests/D2L.CodeStyle.Analyzers.Test/Specs/PatternStringAttributeAnalyzer.cs +++ b/tests/D2L.CodeStyle.Analyzers.Test/Specs/PatternStringAttributeAnalyzer.cs @@ -98,14 +98,19 @@ void SinglePatternTests() { } void NonConstantValuesAreFlagged() { - + #region Non-constant values are flagged as needing to be constant string variable = "123"; - #region Non-constant values are flagged as needing to be constant Digits _ = new( /* PatternStringMustBeConstant() */ variable /**/ ); Digits _ = /* PatternStringMustBeConstant() */ variable /**/; _ = (Digits)/* PatternStringMustBeConstant() */ variable /**/; #endregion + + #region null is treated as non-constant + Digits _ = new( /* PatternStringMustBeConstant() */ null /**/ ); + Digits _ = /* PatternStringMustBeConstant() */ null /**/; + _ = (Digits)/* PatternStringMustBeConstant() */ null /**/; + #endregion } void MultiplePatternTests() {