Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can you read an attribute placed on a const using reflection in C#?

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?

like image 273
KallDrexx Avatar asked Feb 17 '11 18:02

KallDrexx


2 Answers

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)    
}
like image 111
Andrew Hare Avatar answered Nov 17 '22 00:11

Andrew Hare


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'.

like image 1
AakashM Avatar answered Nov 17 '22 02:11

AakashM