0
\$\begingroup\$

Looking for more simple one liner for environment variable check with default value in csharp, any help is appreciated.

public static string GetEnvironmentVariable1(string envName, string defaultValue)
{
   var env = Environment.GetEnvironmentVariable(envName);
   return string.IsNullOrEmpty(env) ? defaultValue : env;
}

Tried this code, but getting compiler error that possible null reference could be returned

public static string GetEnvironmentVariable2(string envName, string defaultValue)
{
  return string.IsNullOrEmpty(Environment.GetEnvironmentVariable(envName)) ? defaultValue : Environment.GetEnvironmentVariable(envName);
}
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

Use ??. Null-coalescing operator.

Null check only

public static string GetEnvironmentVariable(string name, string defaultValue)
    => Environment.GetEnvironmentVariable(name) ?? defaultValue;

Null and empty string check

public static string GetEnvironmentVariable(string name, string defaultValue)
    => Environment.GetEnvironmentVariable(name) is string v && v.Length > 0 ? v : defaultValue;

Pattern matching.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.