Playing with Extensions and Expressions

Posted Thu, Oct 11 2007 0:10 by bill

Expression trees allow you to walk through all the information about an expression.  So you can use this to create a NameOf function similar to the one I outlined in my post on VB 10 thoughts (part 5)


   <Extension()> _

   Function NameOf(Of T1)(ByVal obj As T1, ByVal fn As Expression(Of Func(Of T1, Object))) As String

      Dim op = fn.Body.Cast(Of UnaryExpression).Operand

      Select Case op.NodeType

         Case ExpressionType.Parameter

            Return op.Type.Name

         Case ExpressionType.MemberAccess

            Return op.Cast(Of MemberExpression).Member.Name

         Case Else

            Return Nothing

      End Select

   End Function



   <Extension()> _

   Function Cast(Of T)(ByVal obj As Object) As T

      Return DirectCast(obj, T)

   End Function



To use the method you still need to pass in a lambda, e.g :

Console.WriteLine(obj.NameOf(Function(x) x.FirstName))  'returns "FirstName"

Console.WriteLine(obj.NameOf(Function(x) x)) 'returns obj's Type's Name

Of course this all happens at runtime, so it isn't probably the best way to go about it. But it's fun seeing what you can do with Expressions ;)

Filed under: , , ,