.NET const affects compiled assembly size

Why are the utilities constreplaced with their values ​​at compile time, but then still included in the assembly? At least it shows IL DASM and Reflector.

I am currently using constmany magic numbers and strings to determine to simplify code changes without affecting runtime performance.

Now I know that this does not affect the memory used, but still affects the compiled assembly size, which is crucial, for example, for mobile phone applications.

Another disadvantage is that other people more easily understand magic numbers when viewing disassembled code.

I'm really curious why this particular compiler (Mono, as well as .NET) does this?

+5
source share
2 answers

This behavior is specified in the ECMA-335 standard (of which both .NET and Mono are implementations). Quoting from section II.22.9, “Constant”:

Note that information Constantdoes not directly affect runtime behavior, although it is visible through Reflection (and, therefore, can be used to implement functionality such as System.Enum.ToString). Compilers check this information during compilation when importing metadata, but the value of the constant itself, if used, is embedded in the CIL stream that the compiler generates. There are no CIL instructions to access the table Constantat run time.

const "" (, , ), , .

const -ness , (, - ):

+6

#, const -ness.


?

class Program
{
    public const int C = 0;
    public       int F = 0;

    static void Main(string[] args)
    {
        foreach (FieldInfo field in typeof(Program).GetFields())
        {
            Console.WriteLine("{0}: IsLiteral = {1}", field.Name, field.IsLiteral);
        }
    }
}

:

C: IsLiteral = True
F: IsLiteral = False

, #: , const.

, # Constant. :

C: IsLiteral = False
F: IsLiteral = False

#, const.

, , # C ( "" ):

F: IsLiteral = False

, , #. , .

- , , const.

+2

All Articles