Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When getting a list of properties (via reflection) can we exclude the ReadOnly ones?

This code will get us all the properties of a class:

Dim myPropertyInfo As PropertyInfo()
     = myType.GetProperties((BindingFlags.Public Or BindingFlags.Instance))

or in C#:

PropertyInfo[] myPropertyInfo
     = myType.GetProperties(BindingFlags.NonPublic|BindingFlags.Instance);

But is there a way to get just the properties defined as ReadOnly?

Or, equally, to exclude the ReadOnly properties?

like image 526
hawbsl Avatar asked Oct 21 '25 06:10

hawbsl


1 Answers

Just filter the results to those which have CanWrite as False

Dim items As PropertyInfo() = Me. _
  GetType(). _
  GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public). _
  Where(Function(x) Not x.CanWrite). _
  ToArray() _

Note the above code sample is assuming Visual Studio 2008 or higher and requires an import of System.Linq. If you're using an older version you can do the following

Dim props As PropertyInfo() = Me.GetType().GetProperties(Reflection.BindingFlags.Instance Or Reflection.BindingFlags.Public)
Dim readOnlyProps As New List(Of PropertyInfo)
For Each cur in props 
  If Not cur.CanWrite Then
    readOnlyProps.Add(cur)
  End If
Next
like image 115
JaredPar Avatar answered Oct 24 '25 02:10

JaredPar