简体   繁体   中英

What happens if value exists for NULL which is compared to a environmental variable

I am self learner of C sharp. I have used the code if (Environment.GetEnvironmentVariable("TS_STRIP_DEV") == null) to check whether environmental variable is available or not.The code is checking for the value to be NULL, ie. it does not exist. What if the value exists and the value is equivalent to the string "NULL", "null" or "nul"

In C# the null value is special and bares no relation to a string with "null" as it's value. "null" does not equal null.

If the value may not exist, or it might and could be a string value, which implies it's not set then you need to check for every situation individually, ie

static void Main(string[] args)
{
    string tsStripDev = Environment.GetEnvironmentVariable("TS_STRIP_DEV");

    if (tsStripDev == null || tsStripDev == "null" || tsStripDev == "nul")
        Console.WriteLine("TS_STRIP_DEV was not set");
    else
        Console.WriteLine("TS_STRIP_DEV = {0}", tsStripDev);

    Console.ReadLine();
}

null is different from "null" .

Former means that the value does not exists. ie the object has not been initialized.

For example

string s;

The latter is a value ie the value exists and that value is "null" like

string s = "null";

Here s is initialized and its value is "null". This can be anything like

string s  = "someuser";

Note : null is different from "null" .

null is default value for reference type variable. it means reference type variable is pointing to nothing/no instance .

so

string str; //here str referes no string instance so str contains null.

but if you assign some string then str points to its instance and it willnot be null

string str="null"; //here str is not equals to null but equals to "null"

where as "null" is a string as any other strings.

Solution : You can convert the string to lowercase and then compare

Try This:

if (Environment.GetEnvironmentVariable("TS_STRIP_DEV") != null)
{
  if(!Environment.GetEnvironmentVariable("TS_STRIP_DEV").ToString().
                                             ToLower().Equals("null"))
  {

  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM