views:

557

answers:

1

Hi Friends,

I searched on the forum / Internet for the solution how a PropetryInfo object (of a Public property) can reveal if it has a Private \ Protected Setter ... it was all in vain .... all help I found was about how to "Set" value of a public property having a Private Setter...

I would like to know if I have a PropertyInfo object of a public property, how would I know if its Setter is Non Public?

I tried, in a exception handling block, where I did a GetValue of the PropertyInfo object and then called SetValue by setting the same value back... but to my surprise it worked well and didn error out.

Help would be very much approaciated...

E.g.

Public Class Class1
Public Property HasContextChanged() As Boolean
    Get
        Return _hasContextChanged
    End Get
    Protected Set(ByVal value As Boolean)
        _hasContextChanged = value
    End Set
End Property

Public Function CanWriteProperty(Optional ByVal propName As String = "HasContextChanged") As Boolean
    Dim prInfo As PropertyInfo = Me.GetType.GetProperty(propName)
    If prInfo Is Nothing Then Return False
    If Not prInfo.CanWrite Then
        Return False
    Else
        Try
            Dim value As Object = prInfo.GetValue(ownObj, Nothing)
            prInfo.SetValue(ownObj, value, Nothing) 'Works for Private Setter
        Catch ex As Exception
            Return False 'Not coming here whatsoever
        End Try
    End If
    Return True
End Function

End Class

Thx

Vinit sankhe.

+3  A: 

Once you have the PropertyInfo for the property, you can call its GetSetMethod function to return the MethodInfo for the set accessor. You can then check the MethodInfo's IsPublic property to see if the set accessor is public.

Dim prInfo As PropertyInfo = Me.GetType.GetProperty(propName)
Dim method as MethodInfo = prInfo.GetSetMethod()
If Not method.IsPublic Then
    Return False
Else
    Dim value As Object = prInfo.GetValue(ownObj, Nothing)
    prInfo.SetValue(ownObj, value, Nothing) 'Works for Private Setter
End If
Adam Hughes
Thx man... you made my day... :-)
Very informative, although MSDN (http://msdn.microsoft.com/en-us/library/2ef4d5h3.aspx) says it will only return the MethodInfo "if the set accessor exists and is public". In this case we might want to use the overload (http://msdn.microsoft.com/en-us/library/scfx0019.aspx) that takes a bool indicating whether or not to retrieve non-public setters.
Chris Shouts
I can verify that GetSetMethod() will only return MethodInfo if the accessor exists and is public in .NET 3.5.Good question and great answer. Thanks everyone!
Eric Willis