简体   繁体   中英

NullreferenceException - Object Reference is not set to an instance of a object

I get the Exception: Object Reference is not set to an instance of object.

I have a Globalvariables class that stores one specifik string, if the string is called "OK", then I should be able to load the page, but if the string is "Invalid" I shouldn't be able to Load the page.

In my default page, I have the following Page_load method:

protected void Page_Load(object sender, EventArgs e)
{
    var masterPage = Master;

    if (masterPage != null)
    {
        if (GlobalVariables.Data.StartsWith("OK"))
        {
            //Do stuff
        }
        else
        {
            // Do stuff
        }
    }
}

If I write GlobalGlobalVariables.Data == "OK" it works fine, but if I write like the above i get the error.

I'm fairly certain that you didn't initialize the global variable "GlobalVariables.Data". The .NET compiler will automatically initialize it to null, which is why you're getting the null reference exception. == is a static method (refer back to the operator overload MSDN doc for more if you're curious), which is why it doesn't throw the exception.

This all being said, it seems more like you might want to be using a Boolean, not a string, in this case, but I'm not familiar with your use cases.

It seems like the value of GlobalVariables.Data is not getting set before the Page_Load or it does not have a default value.

Solution 1: Add a default value.

public static class GlobalVariables
{
    private static string _data;

    public static string Data
    {
        get { return _data ?? "Invalid"; }
        set { _data = value; }
    }
}

Usage:

if(GlobalVariables.Data.Equals("Ok", StringComparison.OrdinalIgnoreCase))
{

}
else
{

}

But it sounds like you want a flag, so why not use an enum ?

Solution 2: Enum

public enum DataStatus
{
    Invalid,
    Ok
}

public static class GlobalVariables
{
    public DataStatus DataStatus { get; set; }
}

Usage:

if(GlobalVariables.DataStatus == DataStatus.Ok)
{

}
else
{

}

Try to change code a bit

if (!string.IsNullOrWhiteSpace(GlobalVariables.Data) && GlobalVariables.Data.StartsWith("OK"))
{
    //Do stuff
}
else
{
    // Do stuff
}

First check if your string is assigned to something ant then is it starts with OK symbols.

You should refrain from using the "StartsWith" Method if the starts with part is your whole string. I would suggest doing something like this rather:

//this is a case-insensitive check of what the value might be

    if(!string.IsNullorEmpty(GlobalVariables.Data))
   {       
      if (GlobalVariables.Data.Equals("ok",StringComparison.OrdinalIgnoreCase))
       {
          //Do stuff
       }
    }

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