Unlike Java, C# strings override the == operator:

if (str1 == str2)

If you want a case-insensitive comparison:

if (string.Equals(str1, str2, StringComparison.OrdinalIgnoreCase))
Answer from SLaks on Stack Overflow
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.string.equals
String.Equals Method (System) | Microsoft Learn
The second string to compare, or null. ... true if the value of a is the same as the value of b; otherwise, false. If both a and b are null, the method returns true. The following example demonstrates the Equals method.
🌐
CodeQL
codeql.github.com › codeql-query-help › csharp › cs-null-argument-to-equals
Null argument to Equals(object) — CodeQL query help documentation
In the following example, IsNull will throw a NullReferenceException when o is null. class Bad { bool IsNull(object o) => o.Equals(null); }
🌐
C For Dummies
c-for-dummies.com › blog
Null Versus Empty Strings | C For Dummies Blog
A null string has no values. It’s an empty char array, one that hasn’t been assigned any elements. The string exists in memory, so it’s not a NULL pointer.
🌐
TheDotNetGuide
thedotnetguide.com › home › c#.net › c# string › string.equals() method in c#
Comparing Strings in C# using String.Equals() Method
September 2, 2024 - String.Equals() considers cultural or linguistic differences while performing the comparison. It allows Null Safe comparisons between two stings.
🌐
LinkedIn
linkedin.com › pulse › should-i-use-equals-instead-compare-strings-c-igor-lashchenko
Should I use Equals instead of == to compare strings in C#?
October 19, 2021 - It checks for the null reference and checks if value is null and then runs Object.RefenceEquals which basically does the same as op_Equality (==). Also, in some cases it could run EqualsHelper.
🌐
Reddit
reddit.com › r/learnprogramming › how do i compare a string to null in c++?
r/learnprogramming on Reddit: How do I compare a string to NULL in C++?
September 27, 2019 -

I need to simply check if an object in a string vector is null or not:

std::vector<string> vliwSlots;
//Some inserts...
string vliwSlot = vliwSlots.at(i); //in a for loop
if(vliwSlot != NULL){ //error on this line
    //Do stuff
}

When I compile this I get the following error at :

no match for ‘operator!=’ (operand types are ‘std::__cxx11::string {aka std::__cxx11::basic_string<char>}’ and ‘long int’)

It seems it thinks NULL is a long int. How the heck do I check if a string is null?

Find elsewhere
🌐
Cprogramming
cboard.cprogramming.com › c-programming › 117372-check-if-string-null.html
Check if string is null
Can you tell me how to check if a string is null in C? I tried p != '\0' doent seem to wrk though! It all depends on what you mean, and what p is declared as. That looks like an empty string check to me.
Top answer
1 of 16
408

You may also understand the difference between null and an empty string this way:

Original image by R. Sato (@raysato)

2 of 16
251

"" is an actual string, albeit an empty one.

null, however, means that the String variable points to nothing.

a==b returns false because "" and null do not occupy the same space in memory--in other words, their variables don't point to the same objects.

a.equals(b) returns false because "" does not equal null, obviously.

The difference is though that since "" is an actual string, you can still invoke methods or functions on it like

a.length()

a.substring(0, 1)

and so on.

If the String equals null, like b, Java would throw a NullPointerException if you tried invoking, say:

b.length()


If the difference you are wondering about is == versus equals, it's this:

== compares references, like if I went

String a = new String("");
String b = new String("");
System.out.println(a==b);

That would output false because I allocated two different objects, and a and b point to different objects.

However, a.equals(b) in this case would return true, because equals for Strings will return true if and only if the argument String is not null and represents the same sequence of characters.

Be warned, though, that Java does have a special case for Strings.

String a = "abc";
String b = "abc";
System.out.println(a==b);

You would think that the output would be false, since it should allocate two different Strings. Actually, Java will intern literal Strings (ones that are initialized like a and b in our example). So be careful, because that can give some false positives on how == works.

Top answer
1 of 16
187

string == null compares if the object is null. string.equals("foo") compares the value inside of that object. string == "foo" doesn't always work, because you're trying to see if the objects are the same, not the values they represent.


Longer answer:

If you try this, it won't work, as you've found:

CopyString foo = null;
if (foo.equals(null)) {
    // That fails every time. 
}

The reason is that foo is null, so it doesn't know what .equals is; there's no object there for .equals to be called from.

What you probably wanted was:

CopyString foo = null;
if (foo == null) {
    // That will work.
}

The typical way to guard yourself against a null when dealing with Strings is:

CopyString foo = null;
String bar = "Some string";
...
if (foo != null && foo.equals(bar)) {
    // Do something here.
}

That way, if foo was null, it doesn't evaluate the second half of the conditional, and things are all right.

The easy way, if you're using a String literal (instead of a variable), is:

CopyString foo = null;
...
if ("some String".equals(foo)) {
    // Do something here.
}

If you want to work around that, Apache Commons has a class - StringUtils - that provides null-safe String operations.

Copyif (StringUtils.equals(foo, bar)) {
    // Do something here.
}

Another response was joking, and said you should do this:

Copyboolean isNull = false;
try {
    stringname.equalsIgnoreCase(null);
} catch (NullPointerException npe) {
    isNull = true;
}

Please don't do that. You should only throw exceptions for errors that are exceptional; if you're expecting a null, you should check for it ahead of time, and not let it throw the exception.

In my head, there are two reasons for this. First, exceptions are slow; checking against null is fast, but when the JVM throws an exception, it takes a lot of time. Second, the code is much easier to read and maintain if you just check for the null pointer ahead of time.

2 of 16
33
Copys == null

won't work?

🌐
Dot Net Perls
dotnetperls.com › string-equals
C# - String Equals Examples - Dot Net Perls
Here we compare strings and test equality. The various parts of this code example code not all do the same thing, but each part does compare strings in some way. Part 1 We use instance Equals on the first string—so it must not be null.
🌐
Reddit
reddit.com › r/learnjava › best way to check for null on strings?
Best way to check for null on Strings? : r/learnjava
May 8, 2024 - The real solution here is to not allow null. Use ImmutableMap. ... You seem to try to compare String values with == or !=. This approach does not work reliably in Java as it does not actually compare the contents of the Strings. Since String is an object data type it should only be compared using .equals().
🌐
Coderanch
coderanch.com › t › 387952 › java › avoid-null-pitfalls-comparing-Strings
How do I avoid null pitfalls when comparing Strings? (Beginning Java forum at Coderanch)
If I were checking for a particular constant, I could just do "Joe".equals(name). But either argument could be null in my case. Any ideas would be appreciated, Thanks, Jason. ... Why don't you check if any of the values/variables are false? If any is then don't do the comparison. If none of them is null, use the eqauls() method to do your comparison. Good luck, Bosun · Bosun (SCJP, SCWCD). So much trouble in the world -- Bob Marley ... The way to compare String object contents is to use the equals() method.
🌐
JetBrains
jetbrains.com › help › inspectopedia › StringEqualsEmptyString.html
'String.equals()' can be replaced with 'String.isEmpty()' | Inspectopedia Documentation
For safety, this inspection's quick-fix inserts an explicit null-check when the equals() argument is nullable. Use the option to make the inspection ignore such cases. ... Here you can find the description of settings available for the 'String.equals()' can be replaced with 'String.isEmpty()' inspection, and the reference of their default values.
🌐
Baeldung
baeldung.com › home › java › java string › comparing strings in java
Comparing Strings in Java | Baeldung
June 19, 2024 - The equals() method of StringUtils class is an enhanced version of the String class method equals(), which also handles null values:
🌐
Tutorial Teacher
tutorialsteacher.com › articles › compare-strings-in-csharp
Compare strings in C#
As you can see above, there is no problem with == operator if a string is null. But, calling the Equals() method on null will throw the NullReferenceException.