ReflectorMemberOfT(ExpressionFuncT) Method

Gets the returned member of an expression providing a refactoring-safe way for referencing a field, property, constructor or function method.

Definition

Namespace: KGySoft.Reflection
Assembly: KGySoft.CoreLibraries (in KGySoft.CoreLibraries.dll) Version: 8.1.0
C#
public static MemberInfo MemberOf<T>(
	Expression<Func<T>> expression
)

Parameters

expression  ExpressionFuncT
An expression returning a member.

Type Parameters

T
Type of the returned member in the expression.

Return Value

MemberInfo
A MemberInfo instance that represents the returned member of the expression

Remarks

Similarly to the typeof operator, which provides a refactoring-safe reference to a Type, this method provides a non-string access to a field, property, constructor or function method:

Example

C#
MemberInfo ctorList = Reflector.MemberOf(() => new List<int>()); // ConstructorInfo: List<int>().ctor()
MemberInfo methodIndexOf = Reflector.MemberOf(() => default(List<int>).IndexOf(default(int))); // MethodInfo: List<int>.IndexOf(int) - works without a reference to a List
MemberInfo fieldEmpty = Reflector.MemberOf(() => string.Empty); // FieldInfo: String.Empty
MemberInfo propertyLength = Reflector.MemberOf(() => default(string).Length); // PropertyInfo: String.Length - works without a reference to a string

Constant fields cannot be reflected by this method because the C# compiler emits the value of the constant into the expression instead of the access of the constant field.

To reflect an action method, you can use the MemberOf(ExpressionAction) method.

To reflect methods, you can actually cast the method to a delegate and get its Method property:

Example

C#
MemberInfo methodIndexOf = ((Action<int>)new List<int>().IndexOf).Method; // MethodInfo: List<int>.IndexOf(int) - a reference to a List is required

  Note

Accessing a method by the delegate cast is usually faster than using this method. However, you must have an instance to access instance methods. That means that you cannot use the default operator for reference types to access their instance methods. If the constructor of such a type is slow, then using this method can be more effective to access an instance method.

Exceptions

ArgumentNullExceptionexpression is .
ArgumentExceptionexpression does not return a member.

See Also