Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

constants

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?

like image 228
neuromancer Avatar asked Nov 27 '09 09:11

neuromancer


People also ask

How do you declare constants in C?

The const keyword Variables can be declared as constants by using the “const” keyword before the datatype of the variable. The constant variables can be initialized once only. The default value of constant variables are zero.

How do you define a constant?

Overview. A constant is a value that cannot be altered by the program during normal execution, i.e., the value is constant. When associated with an identifier, a constant is said to be “named,” although the terms “constant” and “named constant” are often used interchangeably.

What is constants in Visual Studio?

A constant is a meaningful name that takes the place of a number or string that does not change. Constants store values that, as the name implies, remain constant throughout the execution of an application. You can use constants that are defined by the controls or components you work with, or you can create your own.

Can you use #define in C#?

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.


1 Answers

public const int NUMBER = 9; 

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

like image 116
Jimmeh Avatar answered Sep 18 '22 19:09

Jimmeh