9

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(); 
}
patrick
  • 16,091
  • 29
  • 100
  • 164
  • Do you mean `if(myObj != null)` ??? Otherwise, `if(T != null)` will produce a compile error: `T` is a Type but used as a variable (something along those lines). – IAbstract Nov 19 '13 at 17:23
  • By "template operator" you mean "generic type parameter", right? – Kendall Frey Nov 19 '13 at 17:24
  • Probably related to [http://stackoverflow.com/questions/3987986/](http://stackoverflow.com/questions/3987986/) – KeyNone Nov 19 '13 at 17:24
  • @BastiM Forcing an item to be non-null is different than simply propagating null to be the result of a method call. – Servy Nov 19 '13 at 17:29

1 Answers1

6

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.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • Don't forget the other 32 possibilities of `Func` and `Action`. This could get ugly quickly. – Kendall Frey Nov 19 '13 at 17:29
  • 1
    @KendallFrey Nope. There's no need for any other overloads to exist. What would you pass to a `Func`? There is only one parameter; it's simply a question of whether or not there is a result. If the caller wants to use a method that has additional parameters they'd need to curry the function to use it. – Servy Nov 19 '13 at 17:31