Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What types can be declared as const?

In C#, which are the types that can be declared as const ?

const int i = 0;
const double d = 0;
const decimal m = 0;
const referenceType = null;

Is there a comprehensive list I can refer?

like image 232
nawfal Avatar asked Jan 30 '26 08:01

nawfal


2 Answers

Well MSDN clearly states that

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.

From section 10.4 of C# language specification. These are the types that can be used.

The type specified in a constant declaration must be sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, decimal, bool, string, an enum-type, or a reference-type. Each constant-expression must yield a value of the target type or of a type that can be converted to the target type by an implicit conversion

like image 79
Ehsan Avatar answered Feb 01 '26 20:02

Ehsan


From MSDN:

Constants are immutable values which are known at compile time and do not change for the life of the program. Constants are declared with the const modifier. Only the C# built-in types (excluding System.Object) may be declared as const. For a list of the built-in types, see Built-In Types Table (C# Reference). User-defined types, including classes, structs, and arrays, cannot be const. Use the readonly modifier to create a class, struct, or array that is initialized one time at runtime (for example in a constructor) and thereafter cannot be changed.

C# does not support const methods, properties, or events.

complete link : http://msdn.microsoft.com/en-us/library/ms173119.aspx

like image 23
gaurav5430 Avatar answered Feb 01 '26 22:02

gaurav5430