Skip to content

Null Reference Exception: Our 3-Hour Adventure

Now I will tell you about a strange event that happened to me, maybe it has happened to you too, who knows? Once upon a time, yes, let’s say a few years ago, I was working on a project. Everything was going quite well, the codes were flowing, and the functions were in their places. The project was almost going live and I was doing the final tweaks. Just when everything seemed fine, it appeared: Null Reference Exception. Ah, that infamous error! As if it was shouting “Hooop, got you!” at the screen.

I tried to understand what had happened at first. The error message was there but figuring out exactly where it was triggered took some time. I opened the debugger, went through the code line by line. Like a detective following clues, but the error was a ghost, constantly escaping. Sometimes, one variable was not null, sometimes it was null. Believe me, it was very frustrating. By the way, I think the weather was pretty hot that day, anyway. It was like… I just couldn’t concentrate properly.

Initially, I thought it was a simple thing. ‘Okay, we’ll just add a null check here and move on,’ I thought. But no… That null reference exception, that damned thing, was like stubbornly fighting me. I fixed it in one place, and it appeared in another. It was like we played a ‘Whack-a-mole’ game with the program, and I was the mole.

Hours started passing. First an hour, then two… By the third hour, things were getting serious. Meanwhile, the project deadline was approaching, and this cursed error just wouldn’t leave me alone. My coffee consumption had also reached its peak. Sometimes, you get stuck on a problem and can’t think of anything else? That was exactly my situation. I can say my own program failed me at that moment.

But giving up was not an option, of course. It was my mistake and I had to fix it. Then I remembered that last issue was similar, I suppose. Anyway. I returned to the beginning, examined the error logs thoroughly. Which function was called, what parameters were passed… looked into details. And finally, I caught a small detail I had overlooked. It seemed a scenario I had never thought of before was triggering, and there, somewhere, an object was not yet created. At that moment, it was as if a lightbulb turned on in my mind.

So, solving that error took exactly 3 hours. Yes, exactly 3 hours! I spent hours just on a simple null check. But what I learned was priceless. Sometimes the solution to the most complex problems is hidden in the simplest details. Meanwhile, I did some research on prevention methods for such errors, and interesting results came up.

First, always check if your variables are null before using them in your code. Sometimes such a simple thing can save a life. Especially when taking data from users, fetching data from an API, or reading from a database, don’t skip this check. When I was making this mistake, I realized that some data wasn’t coming through and I was trying to use non-existent data. What can I say… just like that.

Second, especially in languages like C# learn to use null propagation operators (?. and ??). These operators make your code cleaner and more readable, while significantly reducing null reference errors. For example, think of it like this: `kullanici.Adres.Sehir?.Adi`. This expression will get `Adi` if `kullanici` is not null, `Adres` is not null, and `Sehir` is not null. If any of them is null, it returns ‘null’ without error. Isn’t it nice?

Also, be careful when using async/await structures. During asynchronous operations, errors occurring in some places resulting in nulls and not being properly handled can lead to this error. It’s like a function expecting one thing and encountering another. By the way, there are great explanations about async/await on YouTube, I recommend watching them.

So, that’s what I experienced. An error that took me 3 hours, but it taught me important lessons. Remember, when developing software, always be careful and consider all possibilities. Making mistakes is human, but repeatedly doing the same mistake is not very smart, I suppose. 🙂 By the way, there are tools used to catch such errors, but sometimes your own eyes and logic are the best tools. What do you think?

Now let’s look at a simple code example on how to trigger and fix this error. Suppose we have a structure like this:

public class Adres {     public string Sehir { get; set; } }

public class Kullanici { public string Isim { get; set; } public Adres Adres { get; set; } }

// The error-prone part: public void YazdirSehir(Kullanici kullanici) { Console.WriteLine(kullanici.Adres.Sehir); // NullReferenceException occurs here! }

In this code, if `kullanici` or `kullanici.Adres` is null, the line `kullanici.Adres.Sehir` will throw an error. That’s the curse that took our 3 hours. 🙂

So how can we fix this? The simplest way is to add null checks:

public void YazdirSehirDuzenli(Kullanici kullanici) {     if (kullanici != null && kullanici.Adres != null && kullanici.Adres.Sehir != null)     {         Console.WriteLine(kullanici.Adres.Sehir);     }     else     {         Console.WriteLine("Sehir bilgisi bulunamadı.");     } }

Or, with a more modern approach, using null propagation operators:

public void YazdirSehirModern(Kullanici kullanici) {     var sehir = kullanici?.Adres?.Sehir ?? "Sehir bilgisi bulunamadı.";     Console.WriteLine(sehir); }

Thus, our code becomes shorter and the risk of errors decreases. Sometimes, when reading code, you wonder “How does this work?” but thanks to these operators, complex-looking things are based on very simple logic. Also, discussions and tips about using these operators on Reddit are plentiful and worth checking out.

In conclusion, although Null Reference Exceptions can be annoying, understanding and solving them is part of the development process. The important thing is to learn from these errors and make our code more robust. If anyone else is struggling with this error, I hope this article provides some insight. Isn’t it nice? Helping each other, that’s what it’s all about.