Search code examples
c#blazornullreferenceexception

NullReferenceException, How to initialize member class Blazor


I have a page with with a simple form within it that it bound to my model's member class, I am getting the following error

NullReferenceException: Object reference not set to an instance of an object.

My page(shown below), works fine if I don't use Timelineinfos, but when I do reference it I get the error. So my question is: How should I initialize Timelineinfos?

<div class="row">
    <div class="col-7">
        <EditForm Model="test">
            <InputText @bind-Value="test.Timelineinfos.City"></InputText>
        </EditForm>
    </div>
</div>

@code {
    public testmodel test = new testmodel();

    public class testmodel
    {
        public string Name { get; set; }
        public Timelineinfo Timelineinfos { get; set; }
    };
}


Solution

  • The reason for the exception is that we haven't initialized the value of Timelineinfos, leaving it null, and then try to access a member of it by binding test.Timelineinfos.City. Because there is no instance of Timelineinfos, that amounts to null.City which is, of course, meaningless.

    You may initialize the value a number of ways.

    Via the constructor using an object initializer:

    public testmodel test = new testmodel() { Timelineinfos = new Timelineinfo() };
    

    ... which is syntactic sugar for the following:

    testmodel test = new testmodel();
    test.Timelineinfos = new Timelineinfo();
    

    By implementing a default for the property:

    public Timelineinfo Timelineinfos { get; set; } = new Timelineinfos();
    

    ... which is essentially the same as setting them in the default (parameterless) constructor:

    public testmodel()
    {
        this.Timelineinfos = new Timelineinfos();
    }
    

    In any case, once you have an instance, your NullReferenceException will be no more.