Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

C# Variable Declaration vs Initialization

Understand the difference between declaring and initializing variables in C#, including default values, definite assignment, var inference, nullable reference types, and field initialization.

~5 min readC#
#C##variable declaration#variable initialization#nullability
Diagram showing a variable being declared and then initialized with a value, highlighting the two-step process in C#.

Declaring a variable and initializing it are separate operations in C#, even though they are often combined on one line. The distinction matters because an uninitialized local variable cannot be read before it is assigned, while fields are automatically initialized to a default value. The examples below show the syntax and the practical consequences.

csharp
int number; // declaration only number = 42; // initialization (assignment) int other = 42; // declaration and initialization together

Declaration vs Initialization: The Core Distinction

Declaration introduces a variable and its type into scope. Initialization assigns a value to that variable for the first time. In C#, a variable that is declared but not initialized has a default value, but that default is not always safe to use. For value types, the default is the zero value of that type. For reference types, the default is null.

csharp
int i; // default is 0 bool flag; // default is false double d; // default is 0.0 string s; // default is null object obj; // default is null

The compiler enforces definite assignment. You cannot read a local variable before it has been assigned, even though it has a default value. This rule prevents the accidental use of uninitialized state.

csharp
int x; Console.WriteLine(x); // CS0165: Use of unassigned local variable 'x'

Fields and properties, on the other hand, are automatically initialized to their default values when an object is constructed. The distinction between local variables and fields is a common source of confusion.

What the Compiler Does With an Uninitialized Variable

The compiler tracks whether a local variable has been definitely assigned. If a variable is declared but never assigned, and you attempt to read it, the compiler emits error CS0165. This is a compile-time check, not a runtime behavior.

For fields, the runtime initializes them to the default value before the constructor runs. For example:

csharp
class Example { private int _count; // initialized to 0 automatically private string? _name; // initialized to null automatically }

This difference is important when you design types. A field that is never explicitly initialized is not a bug, but a local variable that is read before assignment is a compile error.

var vs Explicit Type: When Initialization Matters

The var keyword infers the type from the initializer. This means var requires an initialization expression. You cannot declare a variable with var and assign it later without an initial value.

csharp
var value = 10; // inferred as int var text = "hello"; // inferred as string

The following does not compile:

csharp
var number; // CS0818: Implicitly-typed variables must be initialized

Using var forces you to initialize at declaration. This can be a good thing because it avoids the unassigned local variable issue. However, it also means you cannot declare a variable and conditionally assign it in separate branches without a fallback value.

Explicit typing gives you more flexibility:

csharp
int result; if (condition) { result = 1; } else { result = 2; } Console.WriteLine(result); // valid

The compiler's definite assignment analysis understands this pattern. With var, you would need to assign a default value first, which may not be semantically meaningful.

Nullable Reference Types and Initialization Requirements

Nullable reference types were introduced in C# 8, and newer .NET project templates enable them by default. This feature changes how the compiler treats reference type declarations. The compiler warns when a non-nullable field or property is not initialized, and it uses flow analysis to warn about possible null values in local variables.

csharp
class Example { public string Name; // warning CS8618: Non-nullable field 'Name' must contain a non-null value when exiting constructor }

For local variables, the compiler uses flow analysis to determine whether a variable is null before it is used. Consider:

csharp
string? maybeNull = GetValue(); if (maybeNull != null) { Console.WriteLine(maybeNull.Length); // safe }

When you declare a non-nullable reference type, you are making a contract that the variable will never be null. The compiler helps enforce that contract by warning when you assign a possibly null value or when you fail to initialize.

This has a direct impact on how you declare and initialize reference types. A non-nullable reference type that is only declared and not initialized will produce a warning, and the variable may be used in a way that causes a runtime NullReferenceException if you suppress the warning.

Initializing Fields, Properties, and Constructor Parameters

Fields and properties have their own initialization rules. A field can be initialized at declaration or in the constructor. A property can be initialized with a property initializer or in the constructor. The order of initialization matters.

csharp
class Order { private List<Item> _items = new List<Item>(); // field initializer private decimal _total; public Order(decimal total) { _total = total; // constructor assignment } }

Field and property initializers run before the constructor body. A constructor assignment therefore overwrites the value from an initializer.

For read-only fields, you must initialize them either at declaration or in the constructor. You cannot assign them later.

csharp
class Config { private readonly int _port; public Config(int port) { _port = port; // required } }

Object initializers provide a way to set public properties at construction time without writing a constructor for every combination:

csharp
var person = new Person { FirstName = "Ada", LastName = "Lovelace" };

This initialization runs after the constructor body. It requires properties with setters or init accessors; with init accessors (C# 9 and later), object initializers work for immutable types.

Performance and Memory Behavior of Uninitialized Variables

Declaring a variable without initializing it does not add meaningful runtime cost. The compiler's definite assignment check is static and has no runtime overhead. Choosing var over an explicit type also has no runtime effect; the generated IL is the same.

For fields, the CLR zeroes memory when an object is allocated. Reference fields start as null, and numeric fields start as 0. Explicitly initializing a field to its default value, such as int _count = 0;, is redundant and does not change performance.

The real cost comes from initializing large objects or collections. For example, initializing an array with default values is cheap because the runtime fills it with the appropriate default for the element type. But initializing a list with many elements requires allocation and copying. That cost is inherent to the data structure, not to the declaration style.

Common Mistakes and How to Avoid Them

One common mistake is assuming that a local variable has a default value that you can safely read. The compiler prevents this, but the error message can be confusing if you are used to other languages.

Another mistake is using var when the initializer does not clearly convey the type, especially with null:

csharp
var value = null; // error CS0815: Cannot assign <null> to an implicitly-typed variable

To fix this, you must specify the type explicitly:

csharp
string? value = null;

With nullable reference types, a related mistake is declaring a non-nullable variable and assigning a nullable expression. The compiler warns, and you may end up with a null value at runtime if you ignore the warning.

A third mistake is over-initializing fields to their default values. This adds noise without changing behavior. Prefer to rely on the runtime's automatic zero-initialization for fields.

When you need to declare a variable without an immediate value, use explicit typing and ensure the variable is assigned before any read. The compiler will help you verify this.

For example, consider a method that returns a result based on a condition:

csharp
public string GetStatus(bool isReady) { string status; if (isReady) { status = "ready"; } else { status = "not ready"; } return status; }

This compiles without warnings because the compiler sees that status is definitely assigned on all paths. If you used var, you would need to assign an initial value, which might not be meaningful.

The choice between declaration and initialization is not just a stylistic preference. It affects compile-time safety, nullability analysis, and the clarity of your intent. Prefer initializing at declaration when the value is known. Use declaration-only when the value must be computed conditionally, and rely on the compiler's definite assignment rules to keep your code safe.

Try matching browser tools

All tools

Small utilities that fit C# work — they run entirely in this browser tab, so nothing you paste leaves your device.

All C# guides

More in C#

All C# guides

The guides filed next to this one in C#, in library order.