Reputation: 73223
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?
Upvotes: 3
Views: 5790
Reputation: 9460
In the context of C#, a constant is a type of field or local variable whose value is set at compile time and can never be changed at run time. It is similar to a variable by having a name, a value, and a memory location. However, it differs from the variable by its characteristic of getting initialized only once in the application. A constant is declared using the keyword "const".
Constants (C# Programming Guide)
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).
Upvotes: 0
Reputation: 32681
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
Upvotes: 7
Reputation: 13902
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
Upvotes: 2