Is an empty string a null reference?

Why is this code (in my _Load()event form ):

FileVersionInfo vi = FileVersionInfo.GetVersionInfo(_fullPath);
String VersionInfo = vi.FileVersion;
if (VersionInfo.Trim().Equals(String.Empty)) {
    VersionInfo = NO_VERSION_INFO_AVAILABLE;
}
textBoxVersionInfo.Text = VersionInfo;

... give me the following msg error when VersionInfo == ""true?

Error System.NullReferenceException Message = The object reference is not set to the object instance. *

+3
source share
5 answers

There is a nullsustainable way to do this: instead

VersionInfo.Trim().Equals(String.Empty)

records

string.IsNullOrWhiteSpace(VersionInfo)

It will not work if VersionInfo- null, and it will return true if trimming VersionInfoleads to an empty string.

+2
source

Here you should use the method String.IsNullOrEmpty. See MSDN

if (String.IsNullOrEmpty(VersionInfo)) {
    VersionInfo = NO_VERSION_INFO_AVAILABLE;}
+7
source

, , :

  • null ;
  • ; ,
  • , null; ,
  • null.

, . / , , null ( ).

expr.somePropertyFieldOrMethod, expr null 1 , Null Reference.

, , , expr null, , , , , . , " " , .

( , , textBoxVersionInfo, null, , VersionInfo == "" . , , VersionInfo .)


1 , , . .NET , , .

+4

VersionInfo is NULL , VersionInfo.Trim() .

String.IsNullOrEmpty.

VersionInfo NULL,

if(VersionInfo == null)

String.IsNullOrEmpty(VersionInfo)

+2

After your reply to my comment, you know what VersionInfois NULL. Trim () is not String.Emptycalled because it will be executed before checking if it is equal .

Instead, you should use (string.IsNullOrEmpty(VersionInfo) || VersionInfo.Trim().Length < 1)(or string.IsNullOrWhiteSpace(VersionInfo)if you are in .NET 4).

EDIT:

Seeing the answer to another answer that you deleted Trim () and it still doesn't work ... at that moment it will break the Equals call. Try the code mentioned above and it should work fine.

+1
source

All Articles