1

We have a file called "StringExtensions" which works as a "class" which can be used for multiple datasets/models I assume.

Can anyone help understand what this ToSafeString does to a string?

public static string ToSafeString(this object source)
{
    return source?.ToString() ?? string.Empty;
}
Selman Genç
  • 100,147
  • 13
  • 119
  • 184

2 Answers2

9

It checks if the object is not null with source?. If it is not null, then ToString() is called and the result is returned. If it is null, thenstring.Empty returned.

It uses (.?) null conditional and (??) null-coalescing operators.

Igor Yalovoy
  • 1,715
  • 1
  • 17
  • 22
3

Firstly source?. checks to see if the object being passed in is null, if it is that entire portion (source?.ToString()) will return null and due to the ?. operator the .ToString() does not get evaluated. This operator is short hand and is equivalent to writing:

if(source != null) {
  return source.ToString();
} else {
 return null;
}

Next, the null coalescing operator ( ?? ) kicks in and it will return string.Empty instead of just a null if either source or the return from .ToString() was null.

If called with null it will return string.Empty

If called on an object that has a .ToString() method that returns null, it will also return string.Empty

If called with an object that has a value to return from .ToString() it will return that value.

Henry
  • 2,187
  • 1
  • 15
  • 28