Search code examples
c#stringwinformsnullreferenceexceptionversioninfo

An empty string is a null reference?


Why would this code (in my form's _Load() event):

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 err msg when VersionInfo == "" is true?

System.NullReferenceException was unhandled Message=Object reference not set to an instance of an object.*


Solution

  • There is a null-safe way to do this: instead of

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

    write

    string.IsNullOrWhiteSpace(VersionInfo)
    

    It will not crash if VersionInfo is null, and it will return true if trimming VersionInfo results in an empty string.