-2
public partial class IICustomer : IEntity
{
    public int CreatedByEmployeeId { get; set; }

    public virtual IItem IItem { get; set; }
}

public partial class IItem : IEntity
{
    public string ItemName { get; set; }
}

I want to access ItemName through the object of IICustomer.

public void SaveIICustomers(int itemId, [FromBody] IEnumerable<CustomerDto> customers)
{
    IICustomer items = new IICustomer();

    items.IItem.ItemName="Sam"; // exception is thrown here
}

But the above code is throwing a NullReferenceException

Object reference not set to instance of object.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • It could be your `items.IItem` are null. You need to step into it to check. For the snippet you provide, `IICustomer` doesn't do anything on `IItem` when constructed. – Louis Go Feb 27 '20 at 05:45
  • Is there any other `partial` class definition of `IICustomer`? – Paul Kertscher Feb 27 '20 at 05:47
  • From your code there is no telling if an instance of class `IItem` was created somewhere. Since it throws `NullReferenceException` allegedly the answer is 'no' – Fabjan Feb 27 '20 at 05:52
  • @Fabjan Do i have to create a separate object of IItem like IItem it= new IItem(); Then how will i add that value to IICustomer object? – Nikita Chaudhary Feb 27 '20 at 05:55
  • Image that there is a person that has address of another person (property `FriendsAddress` in class `Person`). Now imagine that the address does not exist but you still ask the compiler 'hey please change the address.country to US', guess what is going to happen ? – Fabjan Feb 27 '20 at 05:58
  • 1
    Also an out of topic recommendation is to avoid to add `I` letter before the class name because in most of the languages `I` letter is reserved for the interfaces. – Ovidiu Rudi Feb 27 '20 at 05:58

1 Answers1

2

It happens because your object items.IItem is not yet created, it's null. Only object items is create. If you want to create also the IItem object when your item object is created I recommend you to add an constructor into the class IICustomer like that:

public partial class IICustomer : IEntity
{
    public IICustomer(){
        IItem= new IItem();
    }
    public int CreatedByEmployeeId { get; set; }
    public virtual IItem IItem { get; set; }
}

In this way each time when you'll create an object IICustomer you will create also it's property IItem.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Ovidiu Rudi
  • 191
  • 1
  • 15