patternMinor
Give me thy name, I'll invoke thee
Viewed 0 times
thygivenametheeinvoke
Problem
This generic function invokes a property of a given object by name:
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?
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 FunctionCan 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:
It removes the inline
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.