Can Expression.PropertyOrField be used to access a static property or field?
Asked Answered
J

1

5

The documentation of the expression parameter of Expression.PropertyOrField states that it can be null for static members:

An Expression whose Type contains a property or field named propertyOrFieldName . This can be null for static members.
(Emphasis mine)

However, whenever I pass null I get an ArgumentNullException.

Jack answered 17/7, 2013 at 12:59 Comment(0)
J
8

The documentation of this method is contradictory:

  • The documentation of the expression parameter states that it can be null for static members
  • The documentation of the ArgumentNullException states that it is thrown if expression is null

Fact is:
This method can't be used to get access to static members, the documentation of the expression parameter is incorrect.
Even when an expression with the correct Type is supplied, this method doesn't work as expected, because it only ever looks for instance members.

To access a static field or property, use Expression.MakeMemberAccess instead.

Jack answered 17/7, 2013 at 12:59 Comment(3)
Then is that the only difference between PropertyOrField and MakeMemberAccess that the latter allows for static member access? BTW, doc for MakeMemberAccess is also buggy - it says expression can be null for static members and the exception section says ArgNullException will be thrown if expression is null...Hybridism
@Hybridism MakeMemberAccess appears to have been fixed; it now only says an exception is thrown when member is null. Also, I've filed an issue at github.com/dotnet/dotnet-api-docs/issues/2449.Leprous
seems like PropertyOrField can access private members whereas MakeMemberAccess cannotLayfield

© 2022 - 2024 — McMap. All rights reserved.