CodeGym /Courses /C# SELF /Constants and the var Keyword

Constants and the var Keyword

C# SELF
Level 10 , Lesson 1
Available

1. Constants

A constant is a "magic" variable whose value you can't (and shouldn't!) change after declaring it. Imagine a super-sticky label on your mug that says "Tea Only." Once you slap that label on, you can't swap tea for coffee anymore (at least, not in C#).


const int DaysInWeek = 7;
const string HelloMessage = "Welcome!";
Declaring constants

In these examples, DaysInWeek will always be 7, and HelloMessage is always a greeting. Once you set a constant's value, you can't change it anymore.

Why do we need constants?

  • Code clarity: when you see const double Pi = 3.14159;, there's no doubt it's a constant, not a variable someone might change halfway through the program.
  • Safety: nobody (not even you in a few months) can accidentally overwrite a constant's value.
  • Performance: the C# compiler plugs the constant's value right into the code, so your program runs a bit faster.

Declaration syntax


const type name = value;
Constant declaration syntax
  • Type — any primitive type (int, double, string, char, as well as enums and literals).
  • Name — it's common to use CamelCase or PascalCase. For "magic" constants, sometimes people use all caps and underscores (DAYS_IN_WEEK), but in C# that's not required.

Examples:

const double GRAVITY = 9.81; // acceleration due to gravity, m/s^2
const char DELIMITER = ',';
const string DEVELOPER_NAME = "Ivan Petrov";

Features and limitations of constants

  • The value must be known at compile time. That means you can't declare a constant whose value is calculated while the program is running.
const int NowYear = DateTime.Now.Year; // COMPILATION ERROR!
  • You can only use simple types, string, or enums.
  • You can't make an array, object, method result, etc. a constant.
  • Even expressions that seem "simple" mathematically must be calculated by the compiler, not at runtime.

For example, you can't do this:

const string FullGreeting = "Hello, " + userName; // userName is a variable, not allowed!

But this is totally fine (and recommended):

const string DefaultGreeting = "Hello, user!";

Where do you usually declare constants?

  • At the top of a class (or file), above the methods.
  • In special classes for constants (like public static class Constants).
  • At the class level, if the constant only relates to that class.

Example for our console app:

class Program
{
    const string Welcome = "Welcome to our app!";
    static void Main(string[] args)
    {
        Console.WriteLine(Welcome);
    }
}

Constants and scope

Constants follow the same scoping rules as regular variables: they're only visible in the range where they're declared.

2. The var keyword

The var keyword — it's not a new variable type, just a handy way to let the compiler figure out the variable type from the context.

It's just syntactic sugar — there's no magic here, and after compilation, the variable becomes a regular type.


var age = 23;      // compiler gets: age is int
var name = "Anna"; // compiler gets: string
var price = 99.99; // compiler gets: double
Using var for type inference

Why did var show up?

  • Readability: you don't have to write long types (like Dictionary<string, List<int>>) by hand.
  • Flexibility: makes it easier to change types in the future: fix the right side — the left side with var will adjust automatically.
  • Modern style: pretty much all modern C# projects use var where the type is obvious from the initialization.

When can (and should) you use var

  • When it's totally clear from the right side what type the variable is.
  • When the type is obvious (var price = 100; — it's obviously an int).
  • When the type is super long or complicated (like the result of a LINQ query).
var numbers = new int[] { 1, 2, 3, 4 };
var input = Console.ReadLine(); // input is string (the method returns string)

When is it better NOT to use var

If the type isn't obvious from the right side, your code can get confusing. And if, a month later, you and your teammates can't figure out what type that was, it's better to be explicit.

var mystery = DoSomethingVeryComplicated(); // WHO ARE YOU, mystery???

Here, it's better to specify the type:

string result = DoSomethingVeryComplicated();

Golden rule: use var only where it doesn't hurt readability!

var — only for local variables

The var keyword only works for local variables — inside methods. You can't use var for:

  • method parameters;
  • class properties;
  • constants.

How does var work "under the hood"

  • The C# compiler plugs in the right type at compile time.
  • After compilation, there's no var left.
  • No performance loss: it's just a convenience for the programmer.
var year = 2025; // at compile time becomes: int year = 2025;

Common mistakes when using var

  • Uninitialized variable:
var a; // ERROR: Compiler can't infer the type!
  • Ambiguous initialization:
var list = null; // ERROR: Type of null is undefined!
  • Reusing a variable with different types:
var value = 5; // value is int
value = "Five"; // ERROR: value is already int!

Comparison: explicit types vs var

Scenario Explicit type var
Type is obvious
int age = 42;
var age = 42;
Method returns a complex type
Dictionary<int, string> dict = SomeFunc();
var dict = SomeFunc();
Array
string[] names = ...
var names = ...
Tip:

in most cases, modern projects use var for local variables. For parameters, properties, constants — stick to explicit types.

3. Pitfalls and tips

In C#, people often write magic numbers right in the code ("7", "3.14159", "0.15" and other mysterious digits). That's bad: if the value ever changes, you'll have to hunt down every mention across the whole project. Use constants! It'll make your life easier, and your teammates won't curse you out...

With var there's another extreme: if your whole code is just var everywhere, but you can't see what types are being used — your code gets confusing fast. So use var where it makes sense and is clear from the context, and in other cases, don't be shy about specifying the type.

2
Task
C# SELF, level 10, lesson 1
Locked
Declaring and Using Constants
Declaring and Using Constants
2
Task
C# SELF, level 10, lesson 1
Locked
Working with the var keyword
Working with the var keyword
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION