System

“Object Reference Not Set lớn an instance of an object.” Cast the first stone those who never struggled with this error message when they were a beginner C#/.NET programmer.

Bạn đang xem: System

This infamous and dreaded error message happens when you get a NullReferenceException. This exception is thrown when you try khổng lồ access a member—for instance, a method or a property—on a variable that currently holds a null reference.

But what is a null reference? What are “references” in the first place? How can you stop the NullReferenceException from happening in your code? That’s what we’re going to lớn cover in today’s post.

We’ll start with fundamentals, by giving a brief explanation of what references are in C#/.NET. After that, you’ll learn what null references are. At this point, you’re halfway there khổng lồ seeing the whole picture.

After this round of theoretical definitions, we’ll get to more practical matters, teaching you how khổng lồ avoid the NullReferenceException in practice. Let’s dig in.



What Are References?

We already know that the NullReferenceException is caused by a null reference. But what is a null reference? In what way does it differ from a non-null reference?

In .NET, you can divide data types in two categories: value types và reference types. If you have a variable of a value type, it stores the value itself. Reference types variables, on the other hvà, don’t hold the value itself. They hold a reference that points khổng lồ where the object lives in memory.

If it helps you visualize it better, you can think of a reference as a linking pointing to lớn a web page, or a shortcut pointing to lớn a tệp tin on your computer. Types such as int (& the other numerical primitive types), DateTime, & boolean are value types. That is, structs are value types. Classes are reference types.

So, a reference is what a variable of a reference type contains. These variables can point to “nothing”, though, and that’s what we Gọi a null reference: a reference that doesn’t point lớn any object. When you try lớn call a method or another member on the said variable, you got the NullReferenceException.

>

Understanding the NullReferenceException

Null reference errors are responsible for a good percentage of all application bugs. They are usually very simple problems caused by not adding additional lô ghích to lớn ensure that objects have sầu valid values before using them. Here are some ways to lớn avoid NullReferenceException.

The following code will throw a NullReferenceException if the variable “text” being passed in is null. You can’t điện thoại tư vấn ToUpper() on a null string.

public void MyMethod(string text)

//Throws exception if text == null

if (text.ToUpper() == “Hello World”)

//bởi vì something

You can also have null reference exceptions because any type of object is null. For example, in the code below, the SqlCommvà object is never initialized. Not running a SQL query would be a serious problem for your application. A null string might be something you just ignore & move on. Other times, lượt thích with the SqlCommvà, it could be a fatal issue you don’t want khổng lồ ignore.

SqlCommand command = null;

//Exception! Object reference not mix khổng lồ an instance of an object

comm&.ExecuteNonQuery();

Use the Null Conditional Operator lớn Avoid NullReferenceExceptions

One of the best new additions to C# was the null conditional operator. Instead of having a crazy amount of “variable != null” type checks, you can use the “?” & your code will short circuit and return null instead of throwing the exception. This will make more sense with some examples below:

text?.ToUpper(); //from previous example, would return null

int? length = customerList?.Length; // null if customerList is null

Customer first = customerList?<0>; // null if customerList is null

int? count = customerList?<0>?.Orders?.Count(); // null if customerList, the first customer, or Orders is null

Use Null Coalescing to Avoid NullReferenceExceptions

Another great feature is null coalescing, which is the “??” operator. It works great for providing a default value for a variable that is null. It works with all nullable data types.

The following code throws an exception without the null coalescing. Adding “?? new List()” prevents the “Object reference not mix khổng lồ an instance of an object” exception.

List values = null;

foreach (var value in values ?? new List())

Console.WriteLine(value);

Simple Examples of Null Values Causing Problems

Some of the most comtháng causes are settings, database calls, or API-type calls not returning expected values. For example, you add a new field lớn your database and don’t populate default values for every record. Randomly records get queried, và the code didn’t trương mục for that new field is null. KA-BOOM: Object reference not mix lớn an instance of an object.

Xem thêm: " Đưa Tay Đây Nào Mãi Bên Nhau Bạn Nhé Bản Gốc, Đưa Tay Đây Nào, Mãi Bên Nhau Bạn Nhé

The Golden Rule of Programming

For years I have sầu had a saying that I say khổng lồ my team all the time. I Gọi it the golden rule of programming. I think every new programmer needs a tattoo that says it.

“If it can be null, it will be null”

The good news is that a lot of null reference errors can be avoided by adding additional xúc tích and code to ensure objects are not null before trying khổng lồ use them. Developers should always assume that everything is invalid & be very defensive in their code. Pretover every database gọi is going to lớn fail, every field is going to lớn have messed up data in it. Good exception handling best practices are critical.

Tips to lớn Prevent Null Reference Exceptions

1. Initialize variables with valid values.

2. If a variable can be null, then check for null & handle it appropriately

3. Use the “?” operator on methods when possible. stringvar?.ToUpper();

4. Use tools like Resharper khổng lồ help point out potential null reference exceptions

Avoiding NullReferenceException With C# 8.0’s Nullable Types

One of the main causes of bugs with null reference is the fact that in C every reference type object can be null, all the time. What if you, the developer, had the power khổng lồ say: “I want this string not to be null, ever”? Better yet, what if this decision was enforced by the compiler itself, preventing you và other developers from assigning null to said variable by accident? Sounds nice? Good news, then: this is a real feature of the eighth version of C# called, unsurprisingly, nullable types.

>

The feature works in an ingenious và powerful way. It redefines the reference types as being non-nullable by default—as many argue they should’ve been from the start. Then, it adds a new kind of syntax that allows you khổng lồ define nullable variables (it’s not really new, though, since it’s the same syntax that has been in use for several years for nullable value types.)

To understand better, take a look at the following example:

static int Add(string numbers)

return numbers.Split(“,”).Select(int.Parse).Sum();

In the pre 8.0 version of C#, the code above is dangerous. The numbers variable could be null, which would cause a NullReferenceException when trying lớn use the Split method.

With C# 8.0 nullable reference types feature, you’d be safe. The variable could never be null & the Điện thoại tư vấn to the Split method would never throw. Any attempt of passing null lớn the Add method would result in a compiling error.

But what if you wanted to lớn allow for null in numbers? In that case, you’d just have to add a question mark after the type’s name:

static int Add(string? numbers)

return numbers.Split(“,”).Select(int.Parse).Sum();

Now things change dramatically. Since numbers can now be null, the compiler will nudge you into lớn checking the variable’s value, with a warning (you could turn the warning inkhổng lồ a compiler error, for even more safety):

*

The compiler is letting me know that “numbers” can be null. Possible solutions include:

Using an if-statement khổng lồ ensure the variable has a valid referenceUsing the already-mentioned null-coalescing operator when calling the Split methodMaking the “numbers” variable non-nullable again, by removing the question markSuppress the rule giving us the warning (which would defeat the whole purpose but hey, it’s an option.)

Keep in mind that this feature is opt-in. That is, it comes disabled by mặc định and you have to lớn activate it in your project’s configuration. The reason for that is that shipping the feature already enabled would cause breaking changes in most code bases.

What Are the Next Steps?

Null reference exceptions are a very common problem in .NET và most programming languages. Luckily, we can all blame Tony Hoare. He invented null references and even calls it the billion-dollar mistake.

Jokes apart, how can we avoid such a problem? One alternative sầu is lớn follow my golden rule: if it can be null, it will be null!

Nowadays, fortunately, we can have the help of the compiler itself when fighting against the NullReferenceException. Enable the “nullable reference types” feature in C# 8.0, & that way you’ll be able to prevent things from being null if you wish so. That allows us a fun spin on my old rule: If it can’t be null, it’ll never be null. The compiler won’t allow it!

Do you want khổng lồ know more about C#, exceptions, and other related topics? If so, stay in tune with the thongcongnghetaz.com blogs, since we’re always publishing posts on these topics and more.

thongcongnghetaz.com Prefix: Code Profiler Developers Can Trust

Before you push your code, you must improve the user experience and optimize the bottlenecks. To make this possible, make sure you leverage the power of the tools at your disposal. Take thongcongnghetaz.com tools for instance. thongcongnghetaz.com offers a tool called Prefix, which allows you khổng lồ monitor your web application written in .NET, Java, PHP, Node.js, Pyeo hẹp, or Ruby.

Prefix is a very lightweight code profiler that can help even the most experienced developers in discovering slow SQL queries & even hidden exceptions. With Prefix, developers can validate the performance of their code as it is written. As a result, they push better code lớn chạy thử và receive fewer support tickets.

thongcongnghetaz.com recently introduced Prefix v4 which is still currently in beta. This version is an improved rebuild of the tried và tested profiling tool from thongcongnghetaz.com.

With this new và improved Prefix, developers receive sầu more OS tư vấn, more programming languages, modern .NET profiling, dedicated log viewer, và Prefix is now a native sầu application for Windows and macOS.

Not only that. While you are running your applications, Prefix works its magic in the background providing detailed snapshots of all the website requests.With thongcongnghetaz.com Prefix, you’ll be able to lớn traông xã the performance of your ứng dụng & also find hidden exceptions, slow queries, & other problems. Download Prefix today.