Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to avoid nullable error after created new instance of class

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading