NullReferenceException: Object reference not set to an instance of an object

Question: How do you resolve the error: NullReferenceException: Object reference not set to an instance of an object?

Login to See the Rest of the Answer

The exception above simply means the instance you are trying to use in your application is not initialized. Initialize the object then try to use it.

- In some instances when you are trying to use the Database Context in an event handler, the Null Reference Exception gets thrown. This is because an event handler might detach itself from the Application Context/State resulting in losing State. An example of this is when Programming Apex 7000 Cash Acceptor in a micro-service architecture, every time you insert in the Bill (Money) into the Cash Acceptor the event handler fires if you try to log the outcome of that event into the database using Entity Framework Database _context an error is emitted, that says "You are trying to use a disposed of an object".

The way to solve this problem is by logging the outcome of the event in the Controller. The fix to this is by using SignalR to stream event messages that happen in the Event Handler function, then let the UI post the stream message to the Server Side function in the Controller. This is not the right way to solve the problem, if you have a better solution, post a comment below.


Jim said:

Hello Friends, in some instances where you have defined a List<Objects> myList {get; set;} and this list is not mapped, you might want to initialize the list as List<Objects> myList {get; set;} = new(); in C# 10. This way the object is List of objects is already initialized and will not throw a Null Reference Exception Error.

Posted On: December 23, 2021 15:04:15 PM

© 2024 - ErnesTech - Privacy
E-Commerce Return Policy