I am playing around with reflection and by accident I realized I could place a custom field attribute on a const class variable, then (using reflection) I read the class' fields, find the const with the attribute and perform actions. This is working fine.
I am curious as to why it works fine. Unless I mis-understood how consts work, I thought constants were "compiled out" and all references to that constant became the constant's actual value after compiling. If this is the case, why can reflection still see the const values?
All the references to a const
are compiled away - not the const
declaration itself. Any const
declarations are emitted as part of the IL by the compiler.
Here's an example (notice that the IL retains the const
field).
C#:
class Foo
{
const int i = 0;
}
IL:
.class private auto ansi beforefieldinit Foo
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
}
.field private static literal int32 i = int32(0)
}
I thought constants were "compiled out" and all references to that constant became the constant's actual value after compiling. If this is the case
I would say that this is not the case. A const
is still a fully-fledged member of its class. Consider a library that exposes a public const
. There might not even be any references (within the library itself) to be 'compiled out'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With