.NET, Code

String.Contains looking for an empty string

Here’s another one of those little idiosyncrasies that I run across in coding.  In some ways I’m almost embarrassed to say I never knew this as it’s really quite simple and also well documented, but it’s one of those edge cases that just don’t happen that often and may not be that damaging of a bug if it does sneak through.

The construct I’m talking about is the String.Contains() method.   In .NET it simply returns a true/false on whether the string contains the string parameter passed into it.


string s1 = "This is a nice string";
bool b;
b = s1.Contains("nice"); // returns true;
b = s2.Contains("bad"); // returns false;

All nice and simple. The issue I ran into was when the string I was looking for was an empty string.


b = s1.Contains(""); // returns true

In my application, that requirements were that it should return false. However, this returns true. It is well documented, but not something I really had to deal with before.

Something to keep an eye out for as it could give you some false positives if you’re not careful.

Still learning after all these years.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s