Search code examples
c#.nettry-catchimplicit-typing

Implicitly-Typed Variables in try...catch


I like using implicit typing for almost everything because it's clean and simple. However, when I need to wrap a try...catch block around a single statement, I have to break the implicit typing in order to ensure the variable has a defined value. Here's a contrived hypothetical example:

var s = "abc";

// I want to avoid explicit typing here
IQueryable<ABC> result = null;
try {
    result = GetData();
} catch (Exception ex) { }

if (result != null)
    return result.Single().MyProperty;
else
    return 0;

Is there a way I can call GetData() with exception handling, but without having to explicitly define the type of the result variable? Something like GetData().NullOnException()?


Solution

  • This is a common problem. I recommend that you just stick with your existing solution.

    If you really want an alternative, here it is:

    static T NullOnException<T>(Func<T> producer) where T : class {
      try { return producer(); } catch { return null; } //please modify the catch!
    }
    
    //now call it
    var result = NullOnException(() => GetData());
    

    Please modify this to log the exception or restrict the catch to a concrete type. I do not endorse swallowing all exceptions.

    As this answer is being read a lot I want to point out that this implementation is just of demo-quality. In production code you probably should incorporate the suggestions given in the comments. Write yourself a robust, well-designed helper function that will serve you well for years.