Last active
March 10, 2020 10:56
-
-
Save blockloop/6529200 to your computer and use it in GitHub Desktop.
Ruby-ish *rescue* for C#. Swallowing exceptions in C# is almost always imprudent, but sometimes it's just necessary.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public T Rescue<T>(T defValue, Func<T> fn) | |
{ | |
try | |
{ | |
return fn(); | |
} | |
catch | |
{ | |
return defValue; | |
} | |
} | |
public void Rescue(Action fn) | |
{ | |
try | |
{ | |
fn(); | |
} | |
catch { } | |
} | |
/* | |
* Usage: | |
*/ | |
public void DoSomething(Person person) | |
{ | |
// any exceptions encountered in retrieving SortOrder will result in a return value of 1 | |
// essentially if person, Preferences, DisplaySettings or SortOrder is null 1 is returned | |
var sortOrder = Rescue(1, () => person.Preferences.DisplaySettings.SortOrder); | |
Console.WriteLine(sortOrder); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Simple yet helpful. Thanks!