If I want to take a substring I can do something like this:
myString.SubString(0,3);
But now the code needs a null check before I can safely call SubString. So I write a string extension.
public static string SafeSubString(this string input, int length)
{
if (input == null)
return null;
if (input.Length > length)
return input.Substring(0, length);
return input;
}
Now I can write myString.SafeSubString(3);
and avoid null checks.
My question is, is it possible to use a template operator with extensions and somehow circumvent null checks in object methods generically?
eg.
MyObj.AnyMethod()
Maybe you could replace string with the T
Something like in the neighborhood of this
static void Swap<T>(this T myObj, delegate method)
{
if(myObj != null)
method.invoke();
}
Sure, you can make something like a Use
method, if you want:
public static TResult Use<TSource, TResult>(
this T obj, Func<TSource, TResult> function)
where T : class
{
return obj == null ? null : function(obj);
}
You'd also probably want one for void methods as well:
public static void Use<T>(this T obj, Action<T> action)
where T : class
{
if(obj != null) action(obj);
}
In a language such as F# one could use monads to allow functions to simply propagate null to their results, rather than throwing an exception. In C# it's not quite as pretty, syntax wise.
I'd also be a bit wary of these methods though. You are essentially "swallowing" the null reference error. There may be cases where you'd be doing it anyway, in which this is an okay shortcut, but just be careful with it to ensure that you don't put yourself into a debugging nightmare in which you can't figure out what's null when it shouldn't be.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With