Problem Statement
I've seen something similar with Remora Results, but I can't use it because of the license. My goal is to instantiate a FooBarResult
either from a result or from an error, then pass it to another component. In the other component, it is checked for IsSuccesful
and depending on that, either BadRequest(FooBarResult.ErrorMsg)
or Ok(FooBarResult.Payload)
is executed (just as an example).
I've heard about the Either monad, but I can't really make sense of it. Instead, I tried to do it the simple way with the FooBarResult
class. However, it is not really safe to use, since I could still use the object in the wrong way.
public class FooBarResult
{
public bool IsSuccessful { get; set; }
public string? Payload { get; set; }
public string? ErrorMsg { get; set; }
public FooBarResult(string error)
{
IsSuccessful = false;
ErrorMsg = error;
}
public FooBarResult(string payload) // that won't work
{
IsSuccessful = true;
Payload = payload;
}
}
Question
How can one make a result class, that contains payload and error message, depending on the success of the operation generating the result? Can payload maybe even be a generic T object and the error also?
CodePudding user response:
For the "avoid wrong usage" part, you could do something like this (I personally wouldn't, but hey... )
public class FooBarResult
{
public bool IsSuccessful {get; set;}
// just doing one to demonstrate
private string _payload;
public string Payload
{
// InvalidOperationException is the ...
// "The exception that is thrown when a method call is invalid
// for the object's current state."
get {
if(IsSuccessful) return _payload;
throw new InvalidOperationException();
}
set { _payload = value; }
}
}
See https://dotnetfiddle.net/fqpSQS
For reference:
Mind : This may get you into trouble as soon as you try to serialize / deserialize.