Oct
20
2011

Simple Result Helper Class

User Rating: / 0
PoorBest 

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

Add comment

Although I believe your free to say what you want, please don't abuse either myself or other peoples, be constructive.


Security code
Refresh

Latest Comments

My Twitter

Follow me on twitter