Advantages of using const instead of variables inside methods

后端 未结 8 938
北恋
北恋 2020-12-02 16:09

Whenever I have local variables in a method, ReSharper suggests to convert them to constants:

// instead of this:
var s = \"some string\";
var flags = Bindin         


        
8条回答
  •  星月不相逢
    2020-12-02 17:16

    Constants in C# provide a named location in memory to store a data value. It means that the value of the variable will be known in compile time and will be stored in a single place.

    When you declare it, it is kind of 'hardcoded' in the Microsoft Intermediate Language (MSIL).

    Although a little, it can improve the performance of your code. If I'm declaring a variable, and I can make it a const, I always do it. Not only because it can improve performance, but also because that's the idea of constants. Otherwise, why do they exist?

    Reflector can be really useful in situations like this one. Try declaring a variable and then make it a constant, and see what code is generated in IL. Then all you need to do is see the difference in the instructions, and see what those instructions mean.

提交回复
热议问题