3

I've recently encountered an problem that has me wondering what two double quotes means to the compiler in C#.

string Var, blankVar;

Var = null; //Var is not instantiated or defined.
Var = ""; //Var should be blank or empty, but it is not null.
Var = "house"; //Var is defined as the string value house.
blankVar = ""; //blankVar should be blank or empty, but it is not null.

At this point the compiler should have the value of "house" stored into the string variable Var. The string variable blankVar should be empty.

if (Var.Contains(blankVar)) //if "house" contains "" then..
{
// do something
}

If Var is equal to "house" and does not contain empty (""), why is the compiler still stepping into the if statement?

snapplex
  • 851
  • 3
  • 13
  • 27

1 Answers1

4

Every string contains the empty string. Logically, this makes sense, as every string contains some substring of zero length, including the empty string itself.

The Contains method simply reflects this. See the documentation:

Return Value
Type: System.Boolean
true if the value parameter occurs within this string, or if value is the empty string (""); otherwise, false.

p.s.w.g
  • 146,324
  • 30
  • 291
  • 331
  • One can even argue the documentation is stating the obvious (except, of course, for the OP....). – Jongware Nov 10 '13 at 02:52
  • @Jongware Yeah, it may not be obvious to everybody. I remember when I first learned about the empty set, and that it is a subset of every other set, including itself. It surprised me at the time (though after thinking about it for a bit I realized that it *had* to be that way). – p.s.w.g Nov 10 '13 at 02:57