Please tell me the meaning and merit of adding const.

Asked 1 months ago, Updated 1 months ago, 1 views

C# const precedes the variable type.The value cannot be rewritten.What happens if the price cannot be changed?What does it mean?And what are the benefits?When do I need a const?

namespace test
{
    class program
    {
        static void Main (string[]args)
        {
            const double TAX = 0.08
            int price = 1000;
            double result;

            result=price*TAX;
        }
    }
}

c#

2022-09-30 14:04

4 Answers

Described by the const keyword.

You must not create constants to represent information that is expected to change at any time. For example, do not use constant fields to store service prices, product version numbers, company brand names, etc. These values may change over time.

So I don't think you need to use it very much.

I don't think it's enough to vote negatively, but I don't think it's going to increase speed or efficiency.NET will compile JIT.This means that variables can be compiled by determining accessibility at runtime, so optimization occurs after detecting that they are not changed even if they are not const-specified.


2022-09-30 14:04

The value is guaranteed to remain the same.
Enables you to build code based on that and optimizes based on that, increasing execution speed and execution efficiency


2022-09-30 14:04

There are quite a few variables that should not be rewritten when developing in large groups.
Const is more for programmers than for compilers.


2022-09-30 14:04

When I grep the source code of the oil, I use const

  • Software that controls existing external devices, which describes the specifications of the device (such as the length of the telegraphic message or the meaning of the bit position)
  • DllImport describes the specifications of the external functions (such as fixed buffer size)
  • Magic number in published binary file

and so on.

For , you are unlikely to need to use const to describe anything about the program itself.You can use it to describe "constants derived from something that already has specifications."


2022-09-30 14:04

If you have any answers or tips


© 2022 OneMinuteCode. All rights reserved.