Validating null and string.Empty in C #

This may sound like a noob question, but this:

string var; if (var == null) 

and

 string var; if (var == string.Empty) 

Same?

Duplicate

What is the difference between String.Empty and Null? and in C # should I use String.Empty or Null?

+4
source share
5 answers

@Jay is correct, they do not match. String.IsNullOrEmpty() is a convenient way to check both null and "".

+31
source

No, they do not match.

string.Empty same as "" , which is the actual object: a string of length 0. null means there is no object.

+19
source

they don't match, the implementation of String.IsNullOrEmpty (string) in mscorlib demonstrates this:

 public static bool IsNullOrEmpty(string value) { if (value != null) { return (value.Length == 0); } return true; } 
+6
source

No, it is not. First, it checks to see if the variable was initialized or whether it was set to "null" later. The second checks if the value of the variable is "" (empty). However, you should not use either. Instead, you should use string.IsNullOrEmpty (var).

+3
source

But sometimes you need to know if there is a NULL string, and it does not matter if it is empty (in the OO design). For example, you have a method and it will return NULL or string. , because null means that the operation failed, and an empty string means that there is no result.

In some cases, you want to find out if it worked or not before taking any actions in other objects.

0
source

All Articles