This isn’t XPO related, but just something that I have been using more and more of recently.
Narrowing and Widening overrides can be very handy, in my case I have created a simple helper class called xResult.
Basically this allows me to return type of xResult and allow passing this xResult whereever MyType is required.
When I use it is where I ask a Helper function to obtain some information for me. So in my example I have a function GetCriteria in a base class that returns a xResult.
Now when I call GetCriteria, if there is some interaction which I need to pass back to “cancel” the operation I can return a xResult which has Succeeded as False. Previously the only option I had was to throw an exception and catch it, this of course isn’t a good practice, the other idea could be to return null, however in this case returning null is a perfectly valid result.
I figured I would post it here incase it helped others or if others had any other suggestions regarding this approach.
Public Class xResult(Of T)
Public Shared Narrowing Operator CType(value As T) As xResult(Of T)
Return New xResult(Of T)(value)
End Operator
Public Shared Widening Operator CType(value As xResult(Of T)) As T
Return value.Value
End Operator
Private fValue As T
Public ReadOnly Property Value As T
Get
Return fValue
End Get
End Property
Public Sub New(Value As T)
fValue = Value
fSucceeded = True
End Sub
Private fSucceeded As Boolean
Public ReadOnly Property Succeeded As Boolean
Get
Return fSucceeded
End Get
End Property
Public Sub New()
fValue = Nothing
fSucceeded = False
End Sub
Public Sub New(Message As String)
fValue = Nothing
fMessage = Message
fSucceeded = False
End Sub
Public Sub New(Message As String, ex As Exception)
fValue = Nothing
fException = ex
fSucceeded = False
fMessage = Message
End Sub
Private fMessage As String
Public ReadOnly Property Message As String
Get
Return fMessage
End Get
End Property
Private fException As Exception
Public ReadOnly Property Exception As Exception
Get
Return fException
End Get
End Property
End Class
public class xResult<T>
{
public static explicit operator xResult<T>(T value)
{
return new xResult<T>(Value);
}
public static implicit operator T(xResult<T> value)
{
return Value.Value;
}
private T fValue;
public T Value {
get { return fValue; }
}
public xResult(T Value)
{
fValue = Value;
fSucceeded = true;
}
private bool fSucceeded;
public bool Succeeded {
get { return fSucceeded; }
}
public xResult()
{
fValue = null;
fSucceeded = false;
}
public xResult(string Message)
{
fValue = null;
fMessage = Message;
fSucceeded = false;
}
public xResult(string Message, Exception ex)
{
fValue = null;
fException = ex;
fSucceeded = false;
fMessage = Message;
}
private string fMessage;
public string Message {
get { return fMessage; }
}
private Exception fException;
public Exception Exception {
get { return fException; }
}
}
Add comment