Need Help to get the Value of a Nullable(Of <T>) Property Using Reflection

Need Help to get the Value of a Nullable(Of <T>) Property Using Reflection

Old forum URL: forums.lhotka.net/forums/t/9960.aspx


AndrewR posted on Wednesday, January 19, 2011

Hi All,

I apologize up front as this is more a general .Net question than CSLA.

I have a sub-class that derives from BusinessBase that I am using to implement Auditing. Itt has Nullable(Of Integer) and Nullable(Of Boolean) as some property types. I am using reflection to get the values from the properties and have code like this (which doesn't work):

What I would like to do is check if the property is a nullable(Of T) type, and then check if it has a value, and if it does, get the value and convert it to string, regardless of whether it's Boolean, Int (which are currently the Nullable(Of T) tyeps of properties that I have.

Dim target As T = Me.Clone

 

For Each pi As PropertyInfo In target.GetType().GetProperties

 

If Nullable.GetUnderlyingType(pi.PropertyType) IsNot Nothing Then

 

' property is a Nullable(Of T) for some T

 

' TODO: throwing exception

 

If pi.GetValue(target, Nothing) IsNot Nothing Then

 

' exception thrown:

 

'System.Reflection.TargetInvocationException - Exception has been thrown by the target of an invocation.

 

' use something like property.HasValue

 

'TODO: to get the value and cast it to string

 

Else

value =

String.Empty()

 

End If

 

Else

value = pi.GetValue(target,

Nothing).ToString()

 

End If

 

Next

Dim value As String = String.Empty

 

Dim value As String = String.Empty

 

For Each pi As PropertyInfo In target.GetType().GetProperties

 

If Nullable.GetUnderlyingType(pi.PropertyType) IsNot Nothing Then

 

' property is a Nullable(Of T) for some T

 

' TODO: throwing exception

 

If pi.GetValue(target, Nothing) IsNot Nothing Then

 

' exception thrown:

 

'System.Reflection.TargetInvocationException - Exception has been thrown by the target of an invocation.

 

' use something like property.HasValue

 

'TODO: to get the value and cast it to string

 

Else

value =

String.Empty()

 

End If

 

Else

value = pi.GetValue(target,

Nothing).ToString()

 

End If

 

Next

 

 

Really appreciate some help.

Thanks,

Andrew

Copyright (c) Marimer LLC