Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NullReferenceException when trying to set class property

Basically I have 2 classes, "Manifest" and "BrowserAction", set out like this:

public class BrowserAction
{
    public string default_icon {get; set;}
    public string default_title {get; set;}
    public string default_popup {get; set;}
}


public class Manifest
{
    public BrowserAction browser_action {get; set;}
}

The problem is, that when I try to set an instance of the Manifest class' browser_action.default_popup, like this:

public void setManifest()
{
    Manifest newManifest = new Manifest();
    newManifest.browser_action.default_popup = "popup.html";
}

I get a System.NullReferenceException. I've looked around but I can't seem to find what the problem is. It works fine for other properties of the "Manifest" class that are just strings etc.

If it's relevant, my IDE is MonoDevelop 2.4, with Mono 2.6.7 for my framework.

like image 405
mg33 Avatar asked Feb 03 '26 12:02

mg33


2 Answers

You are accessing property browser_action of newly created instance newManifest that is still null.

Change your example to something like:

public void setManifest()
{
    Manifest newManifest = new Manifest();
    newManifest.browser_action = new BrowserAction();
    newManifest.browser_action.default_popup = "popup.html";
}

I am assuming that BrowserAction has a public accessible constructor with no arguments.

Or in one go:

public void setManifest()
{
    Manifest newManifest = new Manifest()
        {
            browser_action = new BrowserAction()
                {
                    default_popup = "popup.html"
                }
        };
}
like image 90
Jorge Ferreira Avatar answered Feb 06 '26 01:02

Jorge Ferreira


browser_action has not been initialized. Add a parameterless constructor to your Manifest class like this:

public class Manifest
{
    public Manifest()
    {
           this.browser_action = new BrowswerAction;
    }

    public BrowserAction browser_action {get; set;}
}
like image 34
James Hill Avatar answered Feb 06 '26 00:02

James Hill