Static vs Instance string.Equals

As you may or may not know, static methods are usually faster than instance methods. This alone should be a good enough reason to use the static string.Equals method in .NET, but if that doesn’t do it for you, allow me to present a simple example.

string a = "hello";
string b = "hi";
bool result = a.Equals(b);

What is the expected result of these lines? A boolean value of false, of course. And it’d be true if the strings were identical. It’s also false if b is null. But what if a is null?

string a = null;
string b = "hi";
bool result = a.Equals(b);

The above code throws a NullReferenceException, since we are attempting to use the instance method of string.Equals and our instance is null. Effectively we’re calling null.Equals which of course is a NullReferenceException.

The static method is best to use in situations where either string (or both) can be null. Re-writing our code as:

string a = null;
string b = "hi";
bool result = string.Equals(a, b);

Allows the code to run identically in function to the original code but without ever throwing a NullReferenceException for any given string input.


See also