Home > OS >  How to avoid nullable error after created new instance of class
How to avoid nullable error after created new instance of class

Time:01-08

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; }
 }

CodePudding user response:

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 it's 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";
}
  •  Tags:  
  • Related