Skip to content

Instantly share code, notes, and snippets.

@blockloop
Last active March 10, 2020 10:56
Show Gist options
  • Save blockloop/6529200 to your computer and use it in GitHub Desktop.
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.
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);
}
@coin8086
Copy link

Simple yet helpful. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment