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?

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

One can even argue the documentation is stating the obvious (except, of course, for the OP....).
@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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.