Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()?

like image 490
mellamokb Avatar asked Dec 28 '12 17:12

mellamokb


2 Answers

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.

like image 186
usr Avatar answered Sep 28 '22 08:09

usr


Just put your code inside the try:

var s = "abc";

// I want to avoid explicit typing here
try {
    var result = GetData();
    if (result != null)
        return result.Single().MyProperty;
    else
        return 0;
} catch (Exception ex) { }
like image 28
Michael Bray Avatar answered Sep 28 '22 07:09

Michael Bray