HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Give me thy name, I'll invoke thee

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thygivenametheeinvoke

Problem

This generic function invokes a property of a given object by name:

Private Shared Function GetPropertyValueByName(Of TObject, TProperty)(
        ByVal T As TObject,
        ByVal PropertyName As String) As TProperty

        Dim result = GetType(TObject).GetProperties() _
            .Where(
                Function(p) (p.Name = PropertyName) _
                    AndAlso p.CanRead() _
                    AndAlso (p.PropertyType Is GetType(TProperty))
                ).FirstOrDefault()

        If (result IsNot Nothing) Then
            Return CType(result.GetValue(T), TProperty)
        End If

        Return Nothing

    End Function


Can this function be improved in some way? Can it generate some sort of issues I have to be aware of? Can it be improved in terms of readability?

Solution

LINQ has two syntaxes to offer. You've used the method syntax, which I find very neat and useful, but for simpler queries I find the query syntax looks much less bulky in VB.NET:

Dim result = (From p In GetType(TObject).GetProperties()
              Where p.Name = PropertyName _
                  AndAlso p.CanRead() _
                  AndAlso p.PropertyType Is GetType(TProperty)
              Select p) _
             .FirstOrDefault()


It removes the inline Function(p) anonymous function declaration, and leaves it up to the compiler to generate it, which in turns frees your code from some of the boilerplate.

Code Snippets

Dim result = (From p In GetType(TObject).GetProperties()
              Where p.Name = PropertyName _
                  AndAlso p.CanRead() _
                  AndAlso p.PropertyType Is GetType(TProperty)
              Select p) _
             .FirstOrDefault()

Context

StackExchange Code Review Q#114649, answer score: 8

Revisions (0)

No revisions yet.