Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verify that an object has a certain property

Tags:

vb.net

I found C# code for it here

So I tried

Public Function checkProperty(ByVal objectt As Object, ByVal propertyy As String) As Boolean
    Dim type As Type = objectt.GetType
    Return type.GetMethod(propertyy)
End Function

But it throws an error at type.GetMethod(propertyy) saying "Value of type 'System.Reflection.MethodInfo' cannot be converted to 'Boolean'."

What to do?

like image 409
natli Avatar asked Feb 22 '12 17:02

natli


2 Answers

First, C# code checks for presence of a method, not a property. Second, C# code compares return to null:

Public Function checkProperty(ByVal objectt As Object, ByVal propertyy As String) As Boolean
    Dim type As Type = objectt.GetType
    Return type.GetProperty(propertyy) IsNot Nothing
End Function

EDIT To check for fields, change the method as follows:

Public Function checkField(ByVal objectt As Object, ByVal fieldName As String) As Boolean
    Dim type As Type = objectt.GetType
    Return type.GetField(fieldName) IsNot Nothing
End Function
like image 167
Sergey Kalinichenko Avatar answered Dec 06 '22 18:12

Sergey Kalinichenko


it is returning the MethodInfo instead and you can just change it as follow:

Public Function checkProperty(ByVal objectt As Object, ByVal propertyy As String) As Boolean
    Dim type As Type = objectt.GetType
    Return type.GetMethod(propertyy) IsNot Nothing
End Function
like image 28
Simon Wang Avatar answered Dec 06 '22 19:12

Simon Wang