Reputation: 55579
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?
Upvotes: 43
Views: 145110
Reputation: 3
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#
Upvotes: 0
Reputation: 168
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.
Upvotes: 1
Reputation: 145
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;
Upvotes: 0
Reputation: 211
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;
}
Upvotes: 21
Reputation: 2872
public const int NUMBER = 9;
You'd need to put it in a class somewhere, and the usage would be ClassName.NUMBER
Upvotes: 77
Reputation: 2005
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++.
Upvotes: 16