performance - Are arithmetic operations on literals in C# evaluated at compile time? -


very short question couldn't find solution on web right now.

int test = 1 + 2; 

will 1 + 2 performed during run- or compile-time?

reason asking: think people use literal without specifying why has been used or means because not want waste bit performance running calculation , believe calculate happens during compiletime , has no effect on performance:

int nbr = 31536000; //what heck that? 

instead of

int nbr = 365 * 24 * 60 * 60; //i guess know nbr supposed now... 

since examples constant expressions (i.e. consist of constants or constructs evaluate such), be evaluated @ compile time.

a constant-expression expression can evaluated @ compile-time.

the type of constantexpression can 1 of following: sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, enumeration type, or null type.

the following constructs permitted in constant expressions:

  • literals (including null literal).
  • references const members of class , struct types.
  • references members of enumeration types.
  • parenthesized sub-expressions, constant expressions.
  • cast expressions, provided target type 1 of types listed above.
  • the predefined +, , !, , ~ unary operators.
  • the predefined +, , *, /, %, <<, >>, &, |, ^, &&, ||, ==, !=, <, >, <=, , >= binary operators, provided each operand of type listed above.
  • the ?: conditional operator.

Comments