0

I have simple class called Api. Using this class I have created another class called JsonPayloadBody.

 public class Api {
    public string Name { get; set; }
    public string Query { get; set; }
 }

public class JsonPayloadBody
{ 
    public Api Api { get; set; } 
}

public void CreateOrder(Order order)
{                           
   var oPayload = new  JsonPayloadBody();
  
   oPayload.Api.Name = "CREATE";
   oPayload.Api.Query = "CREATE_ORDER";
}

Now I need to set Name and Query values to the above class. But after run my application I got following error.

Exception has occurred: CLR/System.NullReferenceException
An exception of type 'System.NullReferenceException' occurred in MHScaleInboundWebAPI.dll but was not handled in user code: 'Object reference not set to an instance of an object.'    
at MHScaleInboundWebAPI.Controllers.OrderController.CreateOrder(Order order) in C:\Projects\IRM\mhscaleinboundwebapi\Controllers\OrderController.cs:line 30

I think its because of after created new instance all class JsonPayloadBody variable values are null. So I try to avoid this error using this way. I set values as null. but still i am getting same error. so how to avoid this problem using another way. Please help me.

 public class Api {
    public string? Name { get; set; }
    public string? Query { get; set; }
 }
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Klaus Gütter Jan 08 '22 at 12:05

1 Answers1

0

You are correct in thinking that your JsonPayloadBody.Api property is null after you initialize a new JsonPayloadBody instance.

To fix it, you are gonna have to do it again - to initialize the instance, only this time it should be of the Api class - and assign its reference to the property, so it would stop being null:

public void CreateOrder(Order order)
{                           
   var oPayload = new  JsonPayloadBody();
   
   oPayload.Api = new Api(); // Here.
  
   oPayload.Api.Name = "CREATE";
   oPayload.Api.Query = "CREATE_ORDER";
}
AgentFire
  • 8,944
  • 8
  • 43
  • 90