C# - SPLessons

C# Constants and literals

Home > Lesson > Chapter 4
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

C# Constants and literals

C# Constants and literals

shape Description

C# Constants and literals are used to store the data values. Neverthless, the values stored in the constants are fixed and cannot be altered at the time of the execution of the program. Constants can be of any basic data type like an integer constant, a floating constant, a character constant, or a string literal. Const, a keyword, indicates a constant. It describes an entity that cannot be changed at program runtime. Instead, the entity must be fully resolved at compile-time. A constant cannot be reassigned. Literal in C# is a source code representation of a value.

1. Integer Literal

shape Description

Integer Literal can be specified as the number without any fractions. It can be of type int, uint, long or ulong. To specify uint, long and ulong with the suffixes u/U, l/L and ul/UL respectively. No suffix is used for int. An integer literal can be hexadecimal, octal or decimal. To specify hexadecimal and octal integer literals prefixes 0x/0X and o/O are used respectively. No prefix is used for decimal.

2. Floating Point Literals

shape Description

Floating-point literal requires the use of the decimal point followed by the number's fractional component. It can be of type float and double.To specify the float literal, suffix f/F is used and to specify the double literal, suffix d/D is used. C# also allows users to use scientific notation for floating-point numbers for which the exponent part is also added in the floating point number.

3. Character Literal

shape Description

Character literal is enclosed in single quotes. Like 'a' or 'C'. It can be a simple character or a escape sequence. Escape sequences are the special characters which have some meaning and begin with a backslash.

4. String Literal

shape Description

String literal is a set of characters enclosed by double quotes. A string literal also has a format like @" ".

5. Null Literal

shape Description

A null literal contains a null value. The type of a null-literal is the null type. Declaration: It can be declared with a meaningful name of a specific data type and also with a fixed value which cannot be altered at the time of execution.You have to declare and initialize a constant at the same time to avoid an occurrence of an error.

shape Examples

The example provided below shows a simple program. [csharp] using System; namespace SPLessons { class Program { const string obj = "Welcome to SPlessons"; static void Main() { Console.WriteLine(obj); Console.WriteLine(Program.obj); const string txt = ".txt"; Console.WriteLine("Download file here" + txt); } } } [/csharp] Output: