1

I'd like to adapt this solution into an existing utility class of mine - just the GetProperty method. Thing is, my utility class is not generically-typed (i.e. the class declaration does not have a <T> parameter like PropertyHelper does), and I cannot add one for the time being.

In other words, I only want that GetProperty method to be generically-typed, not the whole class.

So what modifications do I need to make the method work? I've tried adding T to the list of generic types for that method:

public static PropertyInfo GetProperty<T, TValue>(Expression<Func<T, TValue>> selector)

But it gives me errors when I try doing the following:

PropertyInfo prop = MyUtilClass.GetProperty<Foo>(x => x.Bar);

Obviously, this is because GetProperty expects a T and a TValue...

I'd simply like to be able to call it like above. How?

Community
  • 1
  • 1
XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
  • 1
    You can't, basically. C# won't let you infer just one type argument. You'll have to have a generic type *somewhere*. – Jon Skeet Feb 05 '13 at 19:08
  • Not sure if any of this old code helps: http://stackoverflow.com/questions/724143/how-do-i-create-a-delegate-for-a-net-property – Tebc Feb 05 '13 at 19:10

1 Answers1

3

I may be off base on this one, but it seems like if you want the code:

PropertyInfo prop = MyUtilClass.GetProperty<Foo>(x => x.Bar);

to work (assuming you're trying to get property info about that "x.Bar"), you would just define your function as:

public static PropertyInfo GetProperty<T>(Expression<Func<T, Object>> selector)

and then from within your function you'd read the name of the member, as in

MemberExpression member = (MemberExpression)selector.Body;
String propertyName = member.Member.Name;
PropertyInfo info = typeof(T).GetProperty(propertyName, BindingFlags.Public 
            |  BindingFlags.Instance)
return info;

Like I said, I may be off base, but that's what it seems like you're trying to do.

sircodesalot
  • 11,231
  • 8
  • 50
  • 83
  • 1
    Thanks. This seems like what I want. However, why change the internals of the method (the third code bit in your answer)? Is there something wrong with the answer I linked? – XåpplI'-I0llwlg'I - Feb 05 '13 at 19:32
  • Actually, no you're fine. In fact I completely forgot you could get the property info data from the MemberExpression itself. Heh. Looks like I learned something too! – sircodesalot Feb 05 '13 at 19:34