System.NullReferenceException in an attribute of type StringBuilder

2

What causes the error to occur? How to correct?

Model:

public class modelExemplo
{
        public StringBuilder listNewsletter { get; set; }

}

Controller:

public ActionResult funcaodeteste()
{
    modelExemplo obj = new modelExemplo();
    obj.listNewsletter.AppendLine("teste1");
    obj.listNewsletter.AppendLine("teste2");    
}
    
asked by anonymous 25.10.2017 / 14:00

3 answers

2

The property object needs to be initialized:

public StringBuilder listNewsletter { get; set; } = new StringBuilder();

If you use an older version of C # you need to do this in a constructor, basic example:

public modelExemplo() {
    listNewsletter = new StringBuilder();
}

Declaring a variable of a type is different from instantiating an object for it. Without an existing object any operation on it will fail.

    
25.10.2017 / 14:03
3

This happens because StringBuilder is a class that is not static , ie needs to be instantiated (initialized). Do this in your builder.

public class modelExemplo
{
        public modelExemplo(){
            listNewsletter = new StringBuilder();
        }

        public StringBuilder listNewsletter { get; set; }

}
    
25.10.2017 / 14:04
2

listNewsletter is null, so listNewsletter.AppendLine will fire a NullReferenceException

You can correct this by initializing listNewsletter in the constructor of your class:

public class modelExemplo
{
    public StringBuilder listNewsletter { get; set; }

    public modelExemplo(){
        listNewsletter = new StringBuilder();
    }

}

I suggest you read this great topic.

    
25.10.2017 / 14:03