3

Ok, some inherited code: I have a struct with a whole load of permissions:

public structure Perms
    dim writeStaff as Boolean
    dim readStaff as Boolean
    dim writeSupervisor as Boolean
    dim readSuperVisor as Boolean
    ' ... and many more
End Structure

And I want a function canDo which I created like so:

public function canDo(p as Perms, whichOne as String) as boolean
    Dim b as System.Reflection.FieldInfo
    b = p.GetType().GetField(whichOne)
    return b
end function

and I call canDo with pre-filled structure and "writeSupervisor" parameters

In debug, b appears as {Boolean writeSupervisor}, but when I try to return b as a Boolean, I get error: Value of type 'System.Reflection.FieldInfo' cannot be converted to 'Boolean'.

Any ideas how I can "index" into a struct by element name and test / compare / return values?

1 Answer 1

4

You need to invoke the GetValue method of the FieldInfo object to obtain the field value.

Public Function canDo(p As Perms, whichOne As String) As Boolean
    If (Not String.IsNullOrEmpty(whichOne)) Then
        Dim info As FieldInfo = p.GetType().GetField(whichOne)
        If (Not info Is Nothing) Then
            Dim value As Object = info.GetValue(p)
            If (TypeOf value Is Boolean) Then
                Return DirectCast(value, Boolean)
            End If
        End If
    End If
    Return False
End Function

I also recommend you read this: Visual Basic Naming Conventions.

Sign up to request clarification or add additional context in comments.

2 Comments

Worked a charm, thanks. Naming: I was just stuffing any old names in example. I have to say though that info.GetValue(p), passing the original object p as parameter, seems very counter-intuitive.
Great! I see what you mean, but you have to remember that the field info object is created by using the type of the object rater than an instance of the object. So p.GetType().GetField(whichOne) is the same as GetType(Perms).GetField(whichOne).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.