C# Constants

In this lesson, you will learn about C# Constants, their usage, and examples to better understand the topic.


C# Constants Explained

Constants are variables that are assigned values at declarations. Once a constant is defined and assigned a value, it cannot be changed.


Example of constants in C#

public const Decimal PI = 3.14M;

Why use Constants?

Use constant when you know your variable will never change in value, such as the PI, number of months in a year, or number of week’s days. Also, constant can be used to make your code cleaner and to avoid magic strings.

For example, you can create a constant PartTime and use it across your application, like the example below.

using System;
public static class Constants {
  public const string PartTime = "Part Time";
}

Later in your code, you can use the constant like this:

If (someField == Constants.PartTime)  // Instread of using someField == "Part Time"

This concludes the C# Constants lesson. In the next lesson, you will learn about how to take input from users in a C# Program.