niico niico - 3 months ago 13
C# Question

Nested classes cause "Object reference not set to an instance of an object. "

I have classes nested within classes in C#.

eg

public class PlaceImages
{
public Guid Id { get; set; }

[Display(Name = "Logo Image")]
public string ImageLogo { get; set; }

[Display(Name = "Background Image")]
public string ImageBackground { get; set; }
}


public class PlaceWithTagsViewModel
{
public string myString { get; set; }
public PlaceText PlaceText { get; set; }
public PlaceImages PlaceImages { get; set; }

}



var myobj = new PlaceWithTagsViewModel()

// This works
myobj.myString = "hello";

// This causes the below error
myobj.PlaceImages.ImageLogo = "imagename.jpg";


"Object reference not set to an instance of an object."


Do I have to initialise the nested objects or something? How can I make this work?

Strangely I can find nothing on Google about this.

Answer
var myobj = new PlaceWithTagsViewModel()

// This works
myobj.myString = "hello";

//You need to initialize PlaceImages also
myobj.PlaceImages= new PlaceImages();

// This causes the below error
myobj.PlaceImages.ImageLogo = "imagename.jpg";

Or you can initialize in constructor also

public class PlaceWithTagsViewModel
{
    public string myString { get; set; }
    public PlaceText PlaceText { get; set; }
    public PlaceImages PlaceImages { get; set; }

  public PlaceWithTagsViewModel()
  {
    this.PlaceImages= new PlaceImages();
  }

}