Course Content
C# Tutorial
About Lesson

Constants and literals

Constants in C# are immutable values that remain unchanged throughout the execution of a program. These values are declared using the const keyword and must be assigned a value at the time of declaration. Once defined, a constant’s value cannot be altered or reassigned during runtime, providing stability and reliability to your code.

Declaring Constants

In C#, constants are declared within a class or a struct and are typically initialized during declaration:

public class ConstantsExample
public const int MaxValue = 100;
public const string ApplicationName = "MyApp";

Key Points about Constants

1. Immutability

Constants are immutable, ensuring that their values remain fixed throughout the program’s execution. Attempting to modify a constant value will result in a compilation error.

2. Compile-time Initialization

Constants must be initialized with a value at the time of declaration, and this value must be determinable at compile-time. This restriction ensures that the value of a constant is known before runtime.

3. Scope

Constants have a scope limited to the block in which they are declared, providing a specific area where their values remain constant and accessible.

Understanding Literals in C#

In C#, literals represent fixed values that are directly used in the code. These can be numeric, string, character, boolean, or null literals.

Types of Literals

1. Numeric Literals

Numeric literals represent numerical values and can be integers, decimals, or floating-point numbers. For instance:

  • int number = 42;
  • double pi = 3.14;

2. String Literals

String literals are sequences of characters enclosed in double quotes (" "). For example:

  • string message = "Hello, World!";

3. Character Literals

Character literals represent a single character enclosed in single quotes (' '). For instance:

  • char grade = 'A';

4. Boolean Literals

Boolean literals represent the logical values true or false.

5. Null Literal

The null literal represents a null reference