-5

Ok, so I am converting someone's code from VB.Net to C#. I was wondering if a string is set to "", is that the same as it being set to null? For example, would the following code:

string word = "";
bool boolValue = false;

if(string == null)
{
  boolValue = true;
}

So would this end up setting boolValue to true, or is setting word to "" or null two different things? My gut feeling tells me that it is different. That "" just makes it an empty string.

  • 6
    why don't you try and find out? – Selman Genç Oct 22 '14 at 16:45
  • 1
    Kind of on the subject, a little known functions is `string.IsNullOrEmpty(myString)` which tests for both conditions. There is also `string.IsNullOrWhiteSpace` which additionally tests for white space. – MikeH Oct 22 '14 at 16:47
  • 2
    Related: [Why is the default value of the string type null instead of an empty string?](http://stackoverflow.com/q/14337551/335858) – Sergey Kalinichenko Oct 22 '14 at 16:48
  • 1
    @alykins Actually they are different. `IsNullOrWhiteSpace` will return true for the string `" "` whereas `IsNullOrEmpty` returns false. – MikeH Oct 22 '14 at 16:50
  • 2
    @Jared.Rodgers This site actually typically encourages you to try and fail before coming here. Which is probably why you're getting a bunch of down votes. I don't mind helping someone learn, but there's a lot to be said for just trying it out (in this case: very easy to do). – MikeH Oct 22 '14 at 16:52
  • it's time that you can learn the **debugging** – Mehdi Khademloo Oct 22 '14 at 16:58
  • @MikeH Ok, I understand now. I'm still a little new to this site. – Jared.Rodgers Oct 22 '14 at 16:58

3 Answers3

9

No, they are definitely not the same thing. "" is an empty string. null is the absence of any value.

.NET has many utility methods that help you check for different cases. You can check out string.IsNullOrEmpty and string.IsNullOrWhitespace.

Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
2

No it's not the same string. If the string is null it's not allocated object. That means you cannot access this string - you will get exception. However, if the string is "" it is allocated object now and you can access this object (you can get Length of that string which will be 0 it this case).

Daniel M
  • 340
  • 2
  • 9
-1

Your confusion probably arises from VB's ambiguous/inconsistent notion of "Nothing" when applied to strings, depending on whether the '=' or 'Is' operator is used, as these examples show:

Dim s1 As String = ""
If s1 = Nothing Then MsgBox("= Nothing") 'true
If s1 Is Nothing Then MsgBox("Is Nothing") 'false

Dim s2 As String = Nothing
If s2 = Nothing Then MsgBox("= Nothing") 'true - both 'Nothing' and "" pass the "= Nothing" test!
If s2 Is Nothing Then MsgBox("Is Nothing") 'true

There is no ambiguity with C# strings.

Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28