//
// OptionalUtilities.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Remora.Results;
namespace NosSmooth.LocalBinding;
///
/// A utilities that work with members that may not be present or may throw an exception.
///
public static class OptionalUtilities
{
///
/// Tries to get value from the function, capturing an exception into Result.
///
/// The function to obtain the value from.
/// The type of the value.
/// The value, or exception error if an exception has been thrown.
public static Result TryGet(Func get)
{
try
{
return get();
}
catch (Exception e)
{
return e;
}
}
///
/// Tries to get value from the function, capturing an exception into Result.
///
/// The function to obtain the value from.
/// The type of the value.
/// The value, or exception error if an exception has been thrown.
public static Result TryIGet(Func> get)
{
try
{
return get();
}
catch (Exception e)
{
return e;
}
}
///
/// Tries to execute an action.
///
/// The action.
/// A result, successful if no exception has been thrown.
public static Result Try(Action get)
{
try
{
get();
return Result.FromSuccess();
}
catch (Exception e)
{
return e;
}
}
}