Simple syntax for getting a member of a type in extension method (C#)

Posted in dotnet, vb, vb.net | No Comments »

I’m trying to write an extension method that will give me the MemberInfo representing a member of a given type, using lambda expressions. Ideally, I’d like to be able to write

var info = MyType.GetMember(m => m.MyProperty);

or, also acceptable

var info = typeof(MyType).GetMember(m => m.MyProperty);

or even

var info = typeof(MyType).GetMember((MyType m) => m.MyProperty);

I have a generic method signature that works, but requires me to specify all the type parameters, and I’d very much like C# to infer them. As far as I can see, if I just find the right way to specify the extension method signature, there should be enough information in (at least the last one of) the code snippets to infer everything – but according to the compiler, there isn’t.

I’ve read an old blog post on static extension methods but I haven’t been able to find anything on it more recent than that. If that came true, I’d be able to write

public static MemberInfo GetMember<TType, TReturnType>(static TType, Expression<Func<TType, TReturnType>> member)

which would solve my problem. But as I said, I seem to be stuck with instance extensions, in which case

public static MemberInfo GetMember<TType, TReturnType>(this Type t, Expression<Func<TType, TReturnType>> member)

just isn’t good enough for the compiler to infer type members.

Similar:

  1. Invoke method dynamically in VB.Net I’ve some classes defined in a dll file. These are in the form of com api. I’m trying to create an object of one of...
  2. Remove objects of some kind of type from a List in C# using extension methods? I wonder if its possible to remove all the objects from the same kind from a generic List using extension methods. something like this code:...
  3. VB.Net Iniatialising a class using System.Reflection and System.Type to create a session based singlton extension method. I have had several occasions recently to access a specific class several times over a relatively small time frame. So I’ve been storing the value...
  4. Entity Framework 4: C# !(ReferenceEquals()) vs != Unless a class specifically overrides the behavior defined for Object, ReferenceEquals and == do the same thing… compare references. In property setters, I have commonly...
  5. bitfield enum extension method to return dictionary of included values Enums can sure be confusing. I am trying to create an extension method on the Enum type that will take a value and return the...

Leave a Reply