How beautiful would it be to do something like:
if (!MyString.IsNull()) return MyString.ToString();I read somewhere a couple of years ago that would be impossible because if the object was null you’d not be allowed to call the method or something like that… But in my head it makes perfect sense.
So I have been refraining myself of doing this for a long time but today I felt brave enough.
The Method Extensions:
public static bool IsNull(this string str) { return str == null; } public static string ToStringSafe(this object obj) { return (obj ?? string.Empty).ToString(); }The main method
static void Main(string[] args) { string str = null; if (str.IsNull()) Console.WriteLine("It was null..."); else Console.WriteLine("It wasn't null..."); Console.WriteLine(str.ToStringSafe()); Console.ReadKey(); }And it works!
The first useful example that comes to my mind
///With this method I won’t have to worry if the object is null or not. Everything is disposed properly!/// Disposes the object if it's not null. /// public static void DisposeSafe(this IDisposable DisposableObject) { if (DisposableObject != null) DisposableObject.Dispose(); }
No comments:
Post a Comment