Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Declaring Constants | Dealing with Data Types
C# Basics
course content

Course Content

C# Basics

C# Basics

1. Getting Started
2. Dealing with Data Types
3. Control Structures
4. Loops
5. Arrays
6. Methods

Declaring Constants

Constants are similar to variables however their value is always set at the declaration time and cannot be changed later.

They are useful in making the code easier to understand by indicating which values do not and are not supposed to be changed throughout the program. Moreover, it minimizes accidental unwanted changes to the data hence reducing bugs in the code.

When declaring a constant we use a similar syntax to variable declaration but we add the keyword const before it:

cs

main

copy
12345678910111213
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { const int myVar = 10; Console.WriteLine(myVar); } } }

If we try to modify a constant, the compiler will show an error:

cs

main

copy
1234567891011121314
using System; namespace ConsoleApp { internal class Program { static void Main(string[] args) { const int myVar = 10; myVar = 20; // Error: The left-hand side of an assignment must be a variable, property or indexer. } } }
question-icon

Complete the code for declaring a constant called `pi` having a value of `3.14`:

Click or drag`n`drop items and fill in the blanks

Everything was clear?

Section 2. Chapter 10
We're sorry to hear that something went wrong. What happened?
some-alt