C
C#2y ago
Esa

❔ Help with designing a functional container object

Hi, I could use some input for a functional container/result object I'm working on. I want it (the struct itself) to never be able to be null or contain null, but this is a situation I'm not quite sure how to handle. It's meant to return the result of invoking a function, but some functions will evaluate to null and I'm not sure how to model that. 🤔 I know that functions that directly accept a T value can throw an exception if that is null as it can be seen in compiletime, but in this case I'm not quite sure what should happen as I cannot check a Func for null until it is actually ran and then it is too late.
public readonly struct Outcome<T> {
private readonly T value;
private readonly string errorMessage
public readonly bool IsSuccess

public static Outcome<T> Of(Func<T> function)
{
if (function == null)
throw new ArgumentNullException(nameof(function));

try
{
var value = function();

if (value == null)
return value == null ? Error("Value cannot be null!") : Success(value);
// throw new ValueIsNullException("Value cannot be null!");

return Success(value);
}
catch (Exception exception)
{
return Error(exception);
}
}
public readonly struct Outcome<T> {
private readonly T value;
private readonly string errorMessage
public readonly bool IsSuccess

public static Outcome<T> Of(Func<T> function)
{
if (function == null)
throw new ArgumentNullException(nameof(function));

try
{
var value = function();

if (value == null)
return value == null ? Error("Value cannot be null!") : Success(value);
// throw new ValueIsNullException("Value cannot be null!");

return Success(value);
}
catch (Exception exception)
{
return Error(exception);
}
}
2 Replies
Esa
Esa2y ago
That ValueIsNullException does not quite make sense in this context, but this is also not meant to allow value to be null. Maybe it would be better to place the Outcome in an error state (by setting IsSuccess to false and value to default)?
Accord
Accord2y ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.