-1

I am having a proeprty class PropUser:

public class PropUser
{
    public int UserId { get; set; }

    public int ParentId { get; set; }

    public PropProduct Product { get; set; }
}

here, 3rd property Product is object of PropProduct which is a another property class

 public class PropProduct
{
    public int ProductId { get; set; }

    public string  Name { get; set; }

    public int Price { get; set; }
}

Now, in below code:

PropUser user = new PropUser();
    user.Product.Name = "Reebok";

user.Product is throwing Exception of "Object reference not set to an instance of an object."

I know user.Product is null, so how to initialize that so that i can set user.Product.Name="Reebok"

donstack
  • 2,193
  • 3
  • 22
  • 39

3 Answers3

3

If you want it initialized as soon as the class is created, create a constructor and initialize it there:

public class PropUser
{
    public PropUser
    {
        Product = new PropProduct();
    }

    public int UserId { get; set; }

    public int ParentId { get; set; }

    public PropProduct Product { get; set; }
}
Grant Winney
  • 61,140
  • 9
  • 100
  • 152
1

You need to initialise the PropProduct object by using the new operator and then assign the values.

Try This:

PropUser user = new PropUser();
user.Product = new PropProduct();
user.Product.Name = "Reebok";
Patrick Hofman
  • 143,714
  • 19
  • 222
  • 294
Sudhakar Tillapudi
  • 24,787
  • 5
  • 32
  • 62
1

If you want to initialize Product as soon as a new PropUser is made, simply add a constructor initializing it in PropUser class.

public class PropUser
{ 
    //Your Properties

    public PropUser() 
    {
        Product = new PropProduct();
    }
}

If you want to do it "on demand" so it can be null sometimes, create a new PropProduct object before or while assigning your string :

PropUser user = new PropUser();
user.Product = new PropProduct {Name = "Reebok"};
Pierre-Luc Pineault
  • 8,363
  • 6
  • 38
  • 53