Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between GetValue, GetConstantValue and GetRawConstantValue

Tags:

c#

reflection

What is the difference between the GetValue, GetConstantValue and GetRawConstantValue methods on the PropertyInfo class? The MSDN documentation unfortunately isn't very clear on the subject.

like image 508
Levi Botelho Avatar asked Aug 07 '13 08:08

Levi Botelho


1 Answers

Both GetConstantValue and GetRawConstantValue are intended for use with literals (think const in the case of fields, but semantically it can apply to more than just fields) - unlike GetValue which would get the actual value of something at runtime, a constant value (via GetConstantValue or GetRawConstantValue) is not runtime dependent - it is direct from metadata.

So then we get to the difference between GetConstantValue and GetRawConstantValue. Basically, the latter is the more direct and primitive form. This shows mainly for enum members; for example - if I had an:

enum Foo { A = 1, B = 2 }
...
const Foo SomeValue = Foo.B;

then the GetConstantValue of SomeValue is Foo.B; however, the GetRawConstantValue of SomeValue is 2. In particular, you can't use GetConstantValue if you are using a reflection-only context, as that would require boxing the value to a Foo, which you can't do when using reflection-only.

like image 121
Marc Gravell Avatar answered Sep 19 '22 01:09

Marc Gravell