5

Strings Contain Empty Strings

 3 years ago
source link: https://www.stevefenton.co.uk/2021/03/strings-contain-empty-strings/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Strings Contain Empty Strings

This is just one of those philosophical moments in programming where one small details can have a big impact. In C# / .NET you will find that when you ask if a string contains an empty string (string.Empty), the answer is yes. This may seem logically surprising so it is worth bearing in mind should you be comparing strings.

// True
bool isMatch = "some string".Contains(string.Empty);

A more realistic example is below, imagine you have a config file with some value, and the value isn’t set for some environment… every comparison made will match.

private string GetItem(string item) {
  // True
  bool isMatch = item.Contains(_config.RudeWord);

  return isMatch ? string.Empty : item;
}

Posted bySteve Fenton16th March 2021Posted inProgrammingTags:c#

Published by Steve Fenton

View all posts by Steve Fenton


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK