tall-needle-56640
04/01/2021, 4:22 PMforeach (var element in Environment.GetEnvironmentVariables())
{
if (element is KeyValuePair<string, object> pair
&& pair.Value is string valueStr)
env[pair.Key] = valueStr;
}
Environment.GetEnvironmentVariables
returns an IDictionary
. Ideally, it would be typed, but generics probably hadn't been introduced yet. I think it's obvious that it should actually return IDictionary<string, string?>
, but in case of any doubt Environment.GetEnvironmentVariable(string)
only returns string?
, not object
. So what value does element is KeyValuePair<string, object>
give us?
Therefore, couldn't the code be simplified to
foreach (var pair in Environment.GetEnvironmentVariables())
{
if (pair.Value is string valueStr)
env[pair.Key] = valueStr;
}
@bored-oyster-3147bored-oyster-3147
04/01/2021, 4:25 PMpair.Key
is string
at compile-time so env[pair.key] = ...;
might give you an error?tall-needle-56640
04/01/2021, 4:44 PMobject
and not string
.bored-oyster-3147
04/01/2021, 5:17 PMelement
is of type System.Collection.DictionaryEntry?
.
And none of them satisfied KeyValuePair<string, object>
, KeyValuePair<string, string>
, or KeyValuePair<string, string?>
... which is concerning
I actually had to do this to get working:
var env = Environment.GetEnvironmentVariables();
foreach (DictionaryEntry? element in env)
{
if (element is null || !element.HasValue)
continue;
if (element.Value.Key is string keyStr
&& element.Value.Value != null
&& element.Value.Value is string valueStr)
Console.WriteLine($"[{keyStr}] = {valueStr}");
}
is KeyValuePair<string, object>
check might never be satisfied currentlyprehistoric-coat-10166
04/01/2021, 5:25 PMSystem.GetEnvironmentVariables
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
should do the trick and then checking the key & valuebored-oyster-3147
04/01/2021, 5:26 PMtall-needle-56640
04/01/2021, 5:29 PMelement.Value.Value != null
&& element.Value.Value is string valueStr
bored-oyster-3147
04/01/2021, 5:31 PMprehistoric-coat-10166
04/01/2021, 5:33 PMif (element.Value.Key is string keyString
&& element.Value.Value is string valueString)
{
env[keyString] = valueString;
}
Should work (with the element null check)enough-garden-22763
04/01/2021, 5:38 PMbored-oyster-3147
04/01/2021, 5:45 PMprehistoric-coat-10166
04/01/2021, 5:46 PMValueWhichMayBeNull ?? ""
Process
https://github.com/dotnet/runtime/issues/34446