System.Nullreferenceexception in an attribute of type Stringbuilder

Asked

Viewed 40 times

2

Why error occurs? How to fix?

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");    
}

3 answers

3

This happens because StringBuilder is a class non-static, that is to say, needs to be instantiated (initialized). Do this in your constructor.

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

        public StringBuilder listNewsletter { get; set; }

}

2


  • Wonder, thank you so much for the answer, it was extremely clear and objective and the best, it worked rs.

2

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

You can fix this by initiating listNewsletter in the builder of his class:

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

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

}

I suggest you take a read in this excellent topic.

  • I’ll look at Arthur, thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.