user192936
user192936

Reputation:

String comparison without null check

I remember long ago reading somewhere that to check a String object against a literal (or a constant, etc.) string, a way to skip null check is:

string a;
// do something
if("some literal string".Equals(a))
    Console.WriteLine("equal");

is preferred rather than

string a;
// do something
if(a!=null && a.Equals("some literal string"))
    Console.WriteLine("equal");

to skip checking against null. However cannot find information about it right now; do you have any objections or concerns about the former one?

Upvotes: 1

Views: 122

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1499740

You're probably thinking about Java, where you need to use equals in order to perform a true value equality check for strings; == would just compare references for identity.

C#, however, has operator overloading - and string overloads == for equality. So it's fine to write:

if (text == "target value")

The == operator handles null on either (or both) sides of the comparison:

  • If both sides are null, the result is true
  • If exactly one side is null, the result is false
  • Otherwise, the strings are compared for ordinal equality

Note, however, that the overload will only be used if the compile-time type of both expressions is string. For example, if you had:

object o = new String("foo".ToCharArray());
if (o == "foo")

... then that will compare references instead of using the overloaded operator.

Upvotes: 8

Matthias
Matthias

Reputation: 12259

I prefer using:

if (String.Equals("Value", a))

It's especially handy when comparing two variables which both can be null - using this static method covers that case as well.

Upvotes: 1

Related Questions