Home > Software design >  Object reference not set to an instance of an object
Object reference not set to an instance of an object

Time:01-03

How to declare and initialize below in a single line.

private MyData model1 = new MyData { Max = 0, Min = 0 };
private MyData model2 = new MyData { Max = 0, Min = 0 };
private MyData model3 = new MyData { Max = 0, Min = 0 };
private MyData model4 = new MyData { Max = 0, Min = 0 };
private MyData model5 = new MyData { Max = 0, Min = 0 };
....

Something like this →

private MyData model1, model2, model3, model4, model5 = new MyData {Max = 0, Min = 0};

Edited:

Only model5 works as others have pointed out.

Initialized models used as below:

private async Task OpenDialog1()
{
    var parameters = new Dictionary<string, object> { { "Title", "Test1" } };
    var request = new ModalRequest { InData = this.model1, Parameters = parameters };
    if (this.modalDialog is not null)
        await modalDialog.ShowAsync<MyForm>(request);
    await JSRuntime.InvokeVoidAsync("printMinMax", this.model1.Min, this.model1.Max);
}

private async Task OpenDialog2()
{
    var parameters = new Dictionary<string, object> { { "Title", "Test2" } };
    var request = new ModalRequest { InData = this.model2, Parameters = parameters };
    if (this.modalDialog is not null)
        await modalDialog.ShowAsync<MyForm>(request);
    await JSRuntime.InvokeVoidAsync("printMinMax", this.model2.Min, this.model2.Max);
}
..............................................

private async Task OpenDialog5()
{
 ....
}

If OpenDialog2() was called, error was thrown at this line

wait JSRuntime.InvokeVoidAsync("printMinMax", this.model2.Min, this.model2.Max);

CodePudding user response:

IEnumerable<MyData> data = Enumerable.Range(0, 5).Select(a => new MyData());

If it really needs to be an array add .ToArray()

    public class MyData
    {
        public int Max { get; set; } = 0;
        public int Min { get; set; } = 0;
    }

CodePudding user response:

The "Object reference not set to an instance of an object" is a pretty famous error and has a very canonical answer. The error is not in the line where you try to initialize the model variables but in later use of the variables model1, model2, model3 and model4 only the last one is created and initialized.

If you were happy with a collection, then there wouldn't be much of a problem. You could create an array for 5 MyData instances and loop over that array to initialize the 5 instances with the same values, but if you want to have 5 separate instances each assigned to 5 different variables names in a single line then, as far as I know, the feature doesn't exist and perhaps there is no real reason to have it. But I don't know if future releases of the language will allow it.

In the meantime there is a possible workaround albeit not the most clear solution. (Still, do you really need it?) It involves the use of a Tuple of 5 MyData

You can implement a static method inside the MyData class that return the 5 initialized variables like here

public class MyData
{ 
    public int Max { get; set; }
    public int Min { get; set; }
    
    public static (MyData model1, MyData model2, MyData model3,  
                   MyData model4, MyData model5)  
                   FiveInstanceFactory(int max, int min)
    {
        MyData[] factory = new MyData[5];
        for (int x = 0; x < factory.Length; x  )
            factory[x] = new MyData {Max = max,Min = min};
            
        return (factory[0], factory[1], factory[2], factory[3], factory[4]);
    }
}

Now you can have your one liner to create the 5 instances with the 5 names you like.

(MyData model1, MyData model2, MyData model3,  
 MyData model4, MyData model5) = MyData.FiveInstanceFactory(0,0);

model1.Max   ;
model2.Min  ;

Console.WriteLine($"Min={model1.Min}, Max={model1.Max}");
Console.WriteLine($"Min={model2.Min}, Max={model2.Max}");

CodePudding user response:

 private var modelList = new List<MyData>();
 for(var i = 0; i < 5; i  )
     modelList.Add(new MyData { Max = 0, Min = 0});

It's not a single line but easier than what are you trying to do.

CodePudding user response:

You can use a loop to initialize multiple instances of MyData with the same values in a single line like this:

    private MyData[] models = new MyData[5]
{
    new MyData { Max = 0, Min = 0 },
    new MyData { Max = 0, Min = 0 },
    new MyData { Max = 0, Min = 0 },
    new MyData { Max = 0, Min = 0 },
    new MyData { Max = 0, Min = 0 }
};

This will create an array of MyData objects with 5 elements, each initialized with the values { Max = 0, Min = 0 }.

Alternatively, you can use a loop to initialize the elements of the array like this:

private MyData[] models = new MyData[5];
for (int i = 0; i < 5; i  )
{
    models[i] = new MyData { Max = 0, Min = 0 };
}

Either way, this will avoid the "Object reference not set to an instance of an object" error you were getting.

  • Related