Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C# Constants

C# Constants

A constant is a value that cannot be reassigned after it is defined in a program. It is usually used to represent fixed data, such as pi, the maximum number of connections, status flags, and so on.

In C#, you can use the const keyword to declare compile-time constants, and you can also represent fixed values directly through literals such as integers, floating-point numbers, characters, and strings.

This section mainly introduces common constant types and literal notations in C#, as well as how to use const to define constants.

Integer Constants

Integer constants are used to represent integers without a fractional part. In C#, integer literals support the following three bases:

**Note:** C# does not support the C/C++ notation of using a leading digit 0 to represent octal integers. For example,0213 represents the decimal integer 213 in C#, not an octal number.

The following are some valid integer constants:



212           // 十进制整数

0xFF          // 十六进制,等于十进制 255

0b1010        // 二进制,等于十进制 10

215U          // 无符号整数

100L          // long 类型整数

100UL         // ulong 类型整数

1_000_000     // 使用下划线分隔数字,提高可读性

The following are some invalid integer constants:



0b102         // 非法:二进制只能包含 0 和 1

0xFG          // 非法:G 不是十六进制数字

032UU         // 非法:不能重复使用 U 后缀

123_          // 非法:下划线不能放在数字末尾

Integer constants can use type suffixes, which are case-insensitive:

Postfix Meaning Example
No suffix Choose, in order, an integer type large enough to hold the value 100
U or u Prefer uint; use ulong if the value is out of range 100U
L or l Prefer long; use ulong if necessary 100L
UL or LU Use the ulong type 100UL

It is generally recommended to use the uppercase form Lto avoid confusion between the lowercase letter l and the digit 1 .

The following example demonstrates integer constants in different bases:

Example

using

System

;

class

Program

{

   

static

void

Main

(

)

   

{

       

int

decimalNumber

=

42

;

       

int

hexNumber

=

0x2A

;

       

int

binaryNumber

=

0b101010

;

        Console

.

WriteLine

(

"Decimal:"

decimalNumber

)

;

        Console

.

WriteLine

(

"Hexadecimal:"

hexNumber

)

;

        Console

.

WriteLine

(

"Binary:"

binaryNumber

)

;

   

}

}

Execution result:

十进制:42

十六进制:42

二进制:42

Although the three integers are expressed in different bases, their actual values are the same.

Floating-point Constants

Floating-point constants are used to represent values with a fractional part or expressed in scientific notation, for example 3.14、0.5 and 1.5e3。

In C#, a floating-point literal can contain an integer part, a fractional part, and an exponent part, and can also be expressed in scientific notation.

Scientific notation uses e or E to represent an exponent with base 10, for example:

1.5e3     // 1.5 × 10³,即 1500

2.5E-2    // 2.5 × 10⁻²,即 0.025

C# provides three commonly used floating-point types:

Type Postfix Example Description
float F or f 3.14f Single-precision floating point, about 6 to 9 significant digits
double D or d (can be omitted) 3.14 Double-precision floating point, about 15 to 17 significant digits
decimal M or m 3.14m High-precision decimal type, suitable for calculations such as currency

The following are some valid floating-point constants:



3.14159       // 合法,double 类型

3.14f         // 合法,float 类型

3.14m         // 合法,decimal 类型

314159E-5     // 合法,科学计数法

210f          // 合法,float 类型,值为 210

1.5e3         // 合法,值为 1500

0.25D         // 合法,double 类型

The following are some invalid floating-point constants:



510E          // 非法:指数部分缺少数字

.e55          // 非法:小数点前后都没有有效数字

3.14L         // 非法:L 只能作为整数后缀

1.2.3         // 非法:包含多个小数点

**Note:** A real literal without a suffix defaults to type double . If you want to assign a literal with a decimal point to a float or decimal variable, you usually need to add the f or m suffix to the description.

Example

using

System

;

class

Program

{

   

static

void

Main

(

)

   

{

       

float

a

=

3

.

14f

;

       

double

b

=

3.1415926

;

       

decimal

c

=

99

.

99m

;

       

double

d

=

1

.

5e3

;

        Console

.

WriteLine

(

"float: "

a

)

;

        Console

.

WriteLine

(

"double: "

b

)

;

        Console

.

WriteLine

(

"decimal: "

c

)

;

        Console

.

WriteLine

(

"Scientific notation: "

d

)

;

   

}

}

Execution result (under a locale that uses a dot as the decimal separator):

float: 3.14

double: 3.1415926

decimal: 99.99

科学计数法: 1500

For scenarios requiring exact decimal calculations such as currency, it is generally recommended to use the decimal type. Note, however, that every numeric type has limits on its range and precision.

Character Constants

Character constants use single quotes '' to represent a character, for example 'A'、'9'、'中'。

In C#, the type of a character literal is char, representing one UTF-16 code unit.

A character constant can be an ordinary character or an escape sequence, for example '\n' representing a newline,'\t' representing a horizontal tab.

Commonly used character escape sequences are as follows:

Escape sequences Meaning
\\ Backslash character \
\' Single quote character '
\" Double quote character "
\0 Null character (Null)
\a Alert character (Alert)
\b Backspace character (Backspace)
\f Form Feed character (Form Feed)
\n Line Feed character (Line Feed)
\r Carriage Return character (Carriage Return)
\t Horizontal Tab character (Tab)
\v Vertical Tab character (Vertical Tab)
\xhh Hexadecimal escape, supporting 1 to 4 hexadecimal digits
\uhhhh Represents a Unicode code unit using 4 hexadecimal digits
\Uhhhhhhhh Represents a Unicode code point using 8 hexadecimal digits

**Note:** C# does not support the \ooo octal character escape sequences found in C, nor does it support \? escape sequences. When you need to represent a question mark, you can directly use '?'。

In addition,char can represent only one UTF-16 code unit. Some Unicode characters (such as many Emoji) require two UTF-16 code units and cannot be stored directly in a single char , so you can use string。

The following example demonstrates common character escape sequences:

Example

using

System

;

class

Program

{

   

static

void

Main

(

)

   

{

       

char

letter

=

'A'

;

       

char

chinese

=

'Center'

;

       

char

unicodeChar

=

'\u4E2D'

;

        Console

.

WriteLine

(

"Normal character:"

letter

)

;

        Console

.

WriteLine

(

"Chinese character:"

chinese

)

;

        Console

.

WriteLine

(

"Unicode character:"

unicodeChar

)

;

        Console

.

WriteLine

(

"Hello\tWorld"

)

;

        Console

.

WriteLine

(

"First line\nSecond line"

)

;

        Console

.

WriteLine

(

"Double quote: ""

)

;

        Console

.

WriteLine

(

"Backslash: \"

)

;

   

}

}

Execution result:

普通字符:A

中文字符:中

Unicode 字符:中

Hello   World

第一行

第二行

双引号:"

反斜杠:\

Where\t represents a horizontal tab; the actual width of the whitespace displayed is determined by the terminal environment;\n represents a newline.

String Constants

A string is used to represent a group of characters. In C#, the string type is string, and ordinary string literals use double quotes "" for enclosure.

C# supports several forms of strings, including ordinary strings, verbatim strings, interpolated strings, and raw strings.

1. Ordinary Strings

Ordinary strings are represented with double quotes and support \n、\t、\\ and other escape sequences.



string a = "hello, world";

string b = "Hello\nWorld";

string c = "Joe said \"Hello\" to me";

string d = "C:\\Users\\Public\\Documents";

2. Verbatim Strings

A verbatim string adds @before the double quotes; usually there is no need to escape backslashes, making it especially suitable for representing Windows file paths, regular expressions, and so on.



string a = @"hello, world";

string b = @"C:\Users\Public\Documents";

string c = @"Joe said ""Hello"" to me";

string d = @"\\server\share\file.txt";

In a verbatim string, backslashes are treated as ordinary characters. If you need to include a double quote, you can use two consecutive double quotes ""。

3. Interpolated Strings

Interpolated strings use the $ prefix, allowing variables or expressions to be embedded directly in the string and avoiding frequent string concatenation.



string name = "Runoob";

int age = 10;



string message = $"名称:{name},年龄:{age}";

4. Raw Strings

Starting with C# 11, you can use three or more double quotes to define a raw string literal.

Raw strings can directly contain backslashes and double quotes, making them suitable for representing multi-line text such as JSON, HTML, and SQL.



string json = """

{

    "name": "Runoob",

    "language": "C#"

}

""";

The double quotes in the above code do not need to be escaped with backslashes. Line breaks and indentation in raw strings follow the syntax rules for C# raw strings.

The following is a comparison of common string forms:

String type Syntax Main Use
Ordinary string "Hello" Ordinary text, escape characters
Verbatim string @"C:\Temp" File paths, regular expressions, multi-line text
Interpolated string $"Hello {name}" Insert variables or expressions into a string
Raw strings """Hello""" Text such as JSON, HTML, and SQL, requires C# 11+

The following example demonstrates the use of ordinary strings, verbatim strings, and interpolated strings:

Example

using

System

;

class

Program

{

   

static

void

Main

(

)

   

{

       

string

name

=

"Runoob"

;

       

// Ordinary string

       

string

a

=

"Hello\nWorld"

;

       

// Verbatim string

       

string

b

=

@"C:\Users\Public"

;

       

// Interpolated string

       

string

c

=

$

"Hello, {name}!"

;

       

// string concatenation

       

string

d

=

"Hello, "

"World!"

;

        Console

.

WriteLine

(

a

)

;

        Console

.

WriteLine

(

b

)

;

        Console

.

WriteLine

(

c

)

;

        Console

.

WriteLine

(

d

)

;

   

}

}

Execution result:

Hello

World

C:\Users\Public

Hello, Runoob!

Hello, World!

**Note:** C# does not automatically concatenate two adjacent string literals into one string. If you need to combine multiple strings, you can use the + operator, interpolated strings, or other string-handling methods.

Defining Constants

In C#, you can use the const The keyword defines a constant.

A constant must be initialized at the time of declaration, and the initialization expression must be a constant expression that can be determined at compile time. Once defined, it cannot be reassigned.

The basic syntax for defining a constant is as follows:

const 数据类型 常量名称 = 常量表达式;

For example:



const int MaxCount = 100;

const double Pi = 3.1415926;

const string SiteName = "Runoob";

const bool IsEnabled = true;

Note thatconst cannot be used for all data types. It can usually be used for numeric types,bool、char、string and enum types. Other reference types can only be declared with a value of null constants.

For data whose initial value must be determined at program runtime, you can consider using readonly。

The following code demonstrates how to define and use constants in a program:

Example

using

System

;

public

class

ConstTest

{

   

class

SampleClass

   

{

       

public

int

x

;

       

public

int

y

;

       

// Define a constant

       

public

const

int

c1

=

5

;

       

public

const

int

c2

=

c1

5

;

       

public

SampleClass

(

int

p1,

int

p2

)

       

{

            x

=

p1

;

            y

=

p2

;

       

}

   

}

   

static

void

Main

(

)

   

{

        SampleClass mC

=

new

SampleClass

(

11

,

22

)

;

        Console

.

WriteLine

(

"x = {0}, y = {1}"

, mC

.

x

, mC

.

y

)

;

        Console

.

WriteLine

(

"c1 = {0}, c2 = {1}"

,

                          SampleClass

.

c1

, SampleClass

.

c2

)

;

   

}

}

When the code above is compiled and executed, it produces the following result:

x = 11, y = 22

c1 = 5, c2 = 10

Program analysis:

If you try to modify an already defined constant, for example:

const int MaxCount = 100;



// This code will produce a compilation error

MaxCount = 200;

the compiler will report that a constant cannot be reassigned.

Difference Between const and readonly

In C#,const and readonly Both can be used to restrict modification of fields, but they differ in when they are initialized and in their scope of use.

Comparison Item const readonly
Initialization Time At compile time Can also be initialized at runtime
Must a value be assigned at declaration? Is No; a value can also be assigned in the constructor
Can it be modified? Cannot be reassigned Cannot be reassigned in ordinary code after initialization
Supported Types Only types that comply with constant declaration rules Supports more data types
Is it a static member? const members in a class are implicitly static Can be an instance field or declared as static readonly
Typical use Fixed mathematical constants, status flags, etc. Fields that are not reassigned after runtime initialization

The following example demonstrates const and readonly differ as follows:

Example

using

System

;

class

Program

{

   

// Compile-time constant

   

const

double

Pi

=

3.14159

;

   

// Read-only field

   

readonly

DateTime createdAt

;

   

// Initialize the readonly field in the constructor

   

public

Program

(

)

   

{

        createdAt

=

new

DateTime

(

2026

,

1

,

1

)

;

   

}

   

static

void

Main

(

)

   

{

        Program obj

=

new

Program

(

)

;

        Console

.

WriteLine

(

"Pi:"

Pi

)

;

        Console

.

WriteLine

(

           

"Creation date:"

obj

.

createdAt

.

ToString

(

"yyyy-MM-dd"

)

       

)

;

   

}

}

Execution result:

圆周率:3.14159

创建日期:2026-01-01

In this example,Pi is a compile-time constant, while createdAt is a read-only field initialized through the constructor when the object is created.

**Note:** For a field of a reference type, readonly the field cannot be made to point to another object after initialization is complete, but this does not mean that the data inside the referenced object cannot be modified.

**Summary:** Literals in C# are used to directly represent fixed values, while const can give compile-time constants names with clear meaning. For values that can be determined at compile time and remain unchanged over the long term, you can use const; for fields that need to be initialized at runtime and cannot be reassigned afterward, you can use readonly。