From 0138013cae5e2b908bac4098ef629fd8fdc1c67c Mon Sep 17 00:00:00 2001 From: Jamie Magee Date: Fri, 17 Apr 2026 11:22:52 -0700 Subject: [PATCH] chore: modernize EnvironmentVariableService Replace string.Compare(.., true) with StringComparison.OrdinalIgnoreCase. Short-circuit to Environment.GetEnvironmentVariable on Windows, where it is already case-insensitive. Drop #nullable disable on the file. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../EnvironmentVariableService.cs | 10 +++++++--- .../IEnvironmentVariableService.cs | 2 +- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs index c89e47024..973a7b668 100644 --- a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs +++ b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs @@ -1,4 +1,3 @@ -#nullable disable namespace Microsoft.ComponentDetection.Common; using System; @@ -13,14 +12,19 @@ public bool DoesEnvironmentVariableExist(string name) return this.GetEnvironmentVariable(name) != null; } - public string GetEnvironmentVariable(string name) + public string? GetEnvironmentVariable(string name) { // Environment variables are case-insensitive on Windows, and case-sensitive on // Linux and MacOS. // https://docs.microsoft.com/en-us/dotnet/api/system.environment.getenvironmentvariable + if (OperatingSystem.IsWindows()) + { + return Environment.GetEnvironmentVariable(name); + } + var caseInsensitiveName = Environment.GetEnvironmentVariables().Keys .OfType() - .FirstOrDefault(x => string.Compare(x, name, true) == 0); + .FirstOrDefault(x => string.Equals(x, name, StringComparison.OrdinalIgnoreCase)); return caseInsensitiveName != null ? Environment.GetEnvironmentVariable(caseInsensitiveName) : null; } diff --git a/src/Microsoft.ComponentDetection.Contracts/IEnvironmentVariableService.cs b/src/Microsoft.ComponentDetection.Contracts/IEnvironmentVariableService.cs index 36918258d..105640319 100644 --- a/src/Microsoft.ComponentDetection.Contracts/IEnvironmentVariableService.cs +++ b/src/Microsoft.ComponentDetection.Contracts/IEnvironmentVariableService.cs @@ -19,7 +19,7 @@ public interface IEnvironmentVariableService /// /// Name of the environment variable. /// Returns a string of the environment variable value. - string GetEnvironmentVariable(string name); + string? GetEnvironmentVariable(string name); /// /// Returns the value of an environment variable which is formatted as a delimited list.