Skip to main content

How to Declare a Variable Now and Assign It Later in C#

· 8 min read
Jagdish Kumawat
Founder @ Dewiride

string advice; declares a variable and gives it no value yet. C# lets you read it only after every path through the code has assigned it, which is how one variable can get its value from an if or an else, or from a try or a catch.

Most of the time a variable gets its value where it's declared, as in int temperature = 31;. Sometimes the value depends on what happens next: an if that picks one value and an else that picks another, or a try that might fail. Then declare the variable first, with no value, and assign it later. The C# reference: To declare a local variable, specify its type and provide its name.

The rule that keeps this safe is in the C# specification: An initially unassigned variable has no initial value. For an initially unassigned variable to be considered definitely assigned at a certain location, an assignment to the variable shall occur in every possible execution path leading to that location. In other words, before a line can read the variable, every way of reaching that line must have assigned it.

Syntax​

Syntax
<Type> <name>;

if (<condition>)
{
<name> = <first value>;
}
else
{
<name> = <second value>;
}

<code that reads the variable>
PartWhat it is
<Type> <name>;The declaration: the type, such as string or int, and the variable's name, with no value
<name> = <first value>;An assignment on one path, here the path where the condition is true
else and <name> = <second value>;An assignment on the other path, so no path is left without one
<code that reads the variable>It compiles only when every path that leads to it has assigned the variable

An if and an else are one way to cover every path. A try that assigns the variable and a catch that assigns it too are another, as the example shows.

The Example​

A console app called DeclareThenAssign declares advice before an if and an else that each give it a value, depending on the temperature. Then it declares pages before a try, so the try and the catch can both assign it, and the line after them can print it.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.

Step 1: Create a Console App​

Terminal
dotnet new console -n DeclareThenAssign
cd DeclareThenAssign
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/DeclareThenAssign/DeclareThenAssign.csproj:
Determining projects to restore...
Restored /Users/you/source/DeclareThenAssign/DeclareThenAssign.csproj (in 44 ms).
Restore succeeded.

dotnet new console -n DeclareThenAssign creates a folder named DeclareThenAssign with a project file and a Program.cs, and cd moves into it. Everything this example uses is part of .NET, so there's no package to add. Open the folder in VS Code, or DeclareThenAssign.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First, the if and the else:

Program.cs (assigned in an if and an else)
int temperature = 31;

// Declared now, with no value. The if and the else each give it one.
string advice;
if (temperature > 25)
{
advice = "wear a hat";
}
else
{
advice = "take a jacket";
}
Console.WriteLine($"It's {temperature} degrees, so {advice}.");

string advice; declares advice with no value. The if gives it one when the temperature is over 25, and the else gives it another in every other case. Whichever path runs, advice has a value before Console.WriteLine reads it.

Then the try and the catch:

Program.cs (assigned in a try and a catch)
string pagesText = "lots";

// Declared before the try, so it's still there after the catch.
int pages;
try
{
pages = int.Parse(pagesText);
}
catch (FormatException)
{
pages = 0;
}
Console.WriteLine($"Pages read from \"{pagesText}\": {pages}");

int.Parse turns text into a number, and throws a FormatException when the text isn't one. pages is declared before the try, because a variable declared inside the try would exist only inside it. The try assigns the number and the catch assigns 0, so pages has a value either way.

Step 3: Run It​

Run it in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
It's 31 degrees, so wear a hat.
Pages read from "lots": 0

macOS-style terminal window titled Terminal — DeclareThenAssign showing dotnet run printing It's 31 degrees, so wear a hat. and Pages read from "lots": 0

At 31 degrees, the if ran, so advice became wear a hat. The text lots isn't a number, so int.Parse threw a FormatException, the catch set pages to 0, and the last line printed Pages read from "lots": 0.

The Complete File​

macOS-style code window titled Program.cs — DeclareThenAssign showing string advice declared with no value and given one by an if and an else, then int pages declared before a try that parses the text lots and a catch for FormatException that sets it to 0, and the two lines that print them

Program.cs
int temperature = 31;

// Declared now, with no value. The if and the else each give it one.
string advice;
if (temperature > 25)
{
advice = "wear a hat";
}
else
{
advice = "take a jacket";
}
Console.WriteLine($"It's {temperature} degrees, so {advice}.");

string pagesText = "lots";

// Declared before the try, so it's still there after the catch.
int pages;
try
{
pages = int.Parse(pagesText);
}
catch (FormatException)
{
pages = 0;
}
Console.WriteLine($"Pages read from \"{pagesText}\": {pages}");

Common Mistakes​

MistakeWhat happensDo this instead
Assigning it in the if only, with no elseerror CS0165: Use of unassigned local variable 'advice'. When the condition is false, nothing assigns advice. The reference: If the compiler detects the use of a variable that might not have been initialized, it generates compiler error CS0165.Assign it on every path: add an else that assigns it too, as in the example
Using var with no value, as in var advice;error CS0818: Implicitly-typed variables must be initialized. The reference: An implicitly typed local variable must be initialized with a value at the same time that it is declared.Write the type: string advice;
Declaring it inside the try, as in int pages = int.Parse(pagesText);error CS0103: The name 'pages' does not exist in the current context on the line after the catchDeclare it before the try, and assign it in the try and in the catch

FAQ​

Does the catch have to assign it?​

Not when it leaves instead. In a check, the catch printed a message and ran return;, with no assignment. It compiled and printed "lots" isn't a number, so the program stops here. The line that reads pages comes after the catch, so the only way to reach it is through the try, which assigned it.

Why does assigning it in a foreach loop give CS0165?​

A check declared string last;, assigned it inside a foreach over three names, and printed it after the loop. The build failed with error CS0165: Use of unassigned local variable 'last'. The array holds three names, but the compiler goes by what a foreach can do: If the source collection of the foreach statement is empty, the foreach statement's body isn't executed and skipped. The CS0165 reference: This error is generated when the compiler encounters a construct that might result in the use of an unassigned variable, even if your particular code does not.

A do loop is different. The reference: Because the loop evaluates that expression after each execution, a do loop executes one or more times. A check that declared int square; and assigned it inside a do loop compiled and printed The first square of 50 or more is 64.

Conclusion​

Declare a variable with its type and no value, as in string advice;, when its value depends on what happens next. Then assign it on every path before any line reads it: in both the if and the else, or in both the try and the catch. If a path can skip the assignment, the build stops with CS0165 instead of letting the program read a value that was never set.

Additional Resources​