How to Define Constants in Visual C# Like #Define in C?
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 C# Doesn't Do This...
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 C# doesn't do this. How is it done?
7 Answers
public const int NUMBER = 9;
You'd need to put it in a class somewhere, and the usage would be ClassName.NUMBER
You can't do this in C#. Use a const int instead.
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;
}
Check How to: Define Constants in C# on MSDN:
In C# the
#definepreprocessor directive cannot be used to define constants in the way that is typically used in C and C++.
in c language: #define (e.g. #define counter 100)
in assembly language: equ (e.g. counter equ 100)
in c# language: according to msdn refrence:
You use #define to define a symbol. When you use the symbol as the expression that's passed to the #if directive, the expression will evaluate to true, as the following example shows:
# define DEBUG
The #define directive cannot be used to declare constant values as is typically done in C and C++. Constants in C# are best defined as static members of a class or struct. If you have several such constants, consider creating a separate "Constants" class to hold them.
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." ( )
Initialize constants at time of declaration since there is no changing them.
public const int cMonths = 12;
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#