How to define constants in Visual C# like #define in C?

后端 未结 7 897
情歌与酒
情歌与酒 2020-12-29 18:53

In C you can define constants like this

#define NUMBER 9

so that wherever NUMBER appears in the program it is replaced with 9. But Visual

相关标签:
7条回答
  • 2020-12-29 19:41

    In C#, per MSDN library, we have the "const" keyword that does the work of the "#define" keyword in other languages.

    "...when the compiler encounters a constant identifier in C# source code (for example, months), it substitutes the literal value directly into the intermediate language (IL) code that it produces." ( https://msdn.microsoft.com/en-us/library/ms173119.aspx )

    Initialize constants at time of declaration since there is no changing them.

    public const int cMonths = 12;
    
    0 讨论(0)
  • 2020-12-29 19:42
    public const int NUMBER = 9;
    

    You'd need to put it in a class somewhere, and the usage would be ClassName.NUMBER

    0 讨论(0)
  • 2020-12-29 19:46

    You can't do this in C#. Use a const int instead.

    0 讨论(0)
  • 2020-12-29 19:47

    Check How to: Define Constants in C# on MSDN:

    In C# the #define preprocessor directive cannot be used to define constants in the way that is typically used in C and C++.

    0 讨论(0)
  • 2020-12-29 19:49
    static class Constants
    {
        public const int MIN_LENGTH = 5;
        public const int MIN_WIDTH  = 5; 
        public const int MIN_HEIGHT = 6;
    }
    
    // elsewhere
    public CBox()
    {
        length = Constants.MIN_LENGTH; 
        width  = Constants.MIN_WIDTH; 
        height = Constants.MIN_HEIGHT;  
    }
    
    0 讨论(0)
  • 2020-12-29 19:53

    What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)

    Also, Python's convention for constants CONSTANT_NAME is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";

    Source: Defining constants in C#

    0 讨论(0)
提交回复
热议问题