C# variable
last modified October 18, 2026
In this article we show how to work with variables in C#. The C# tutorial is a comprehensive tutorial on the C# language.
A variable is a storage location. A variable has a name and a data type. The data type determines what values can be assigned to the variable, for instance integers, strings, or boolean values. Over the lifetime of the program, a variable can hold various values of the same data type.
C# is statically typed: the type of every variable is known at compile time, and the compiler rejects assignments of incompatible values.
Variable names must be valid C# identifiers. They must start with a letter or an
underscore, and may contain Unicode letters, decimal digits, and some connecting
and combining characters. Names are case sensitive, so age and
Age are different variables. A keyword can be used as a name when
prefixed with @. By convention, local variables and parameters use
camelCase, while public members use PascalCase.
C# variable example
In the first example, we define several variables.
string city = "Berlin"; string name = "Peter"; int age = 36; string nationality = "German"; Console.WriteLine(city); Console.WriteLine(name); Console.WriteLine(age); Console.WriteLine(nationality); city = "London"; Console.WriteLine(city); int x = 1, y = 2, z; // several variables in one declaration z = x + y; Console.WriteLine(z);
In the example, we declare and use several variables.
string city = "Berlin";
We declare a city variable of the string type and
initialize it to the "Berlin" value.
city = "London";
We assign a new value to the city variable.
int x = 1, y = 2, z; z = x + y;
Several variables of the same type can be declared in one statement. The variable
z has no value until it is assigned. For readability, one declaration
per line is usually better.
$ dotnet run Berlin Peter 36 German London 3
C# variable - var keyword
Variables can be implicitly typed with the var keyword. The variables
are still strongly typed; the compiler infers the type from the right side of the
assignment. A var variable must be initialized in its declaration.
var name = "Lucia";
var age = 27;
var prices = new List<decimal> { 9.99m, 4.5m };
var point = (X: 3, Y: 4);
Console.WriteLine($"{name} is {age} years old");
name = "Robert";
age = 42;
Console.WriteLine($"{name} is {age} years old");
Console.WriteLine(name.GetType());
Console.WriteLine(age.GetType());
Console.WriteLine(prices.GetType());
Console.WriteLine(point.GetType());
// target-typed new: the type is on the left
List<string> words = new() { "owl", "falcon" };
Console.WriteLine(words.Count);
// age = "old"; // error CS0029: cannot convert string to int
In the example, we have several implicitly typed variables.
var name = "Lucia"; var age = 27;
The name variable is of the string type, and
age is an int. The type can never change; the commented
line age = "old" would not compile.
List<string> words = new() { "owl", "falcon" };
When the type is spelled out on the left side, the target-typed new()
expression lets us omit it on the right side. Use var when the type
is obvious from the right side, and an explicit type when it is not.
$ dotnet run Lucia is 27 years old Robert is 42 years old System.String System.Int32 System.Collections.Generic.List`1[System.Decimal] System.ValueTuple`2[System.Int32,System.Int32] 2
C# variable default values
The fields of a class and the elements of an array are automatically set to the
default value of their type: zero for numbers, false for booleans,
and null for references. Local variables, in contrast, get no default
value. The compiler requires definite assignment: a local variable must be
assigned before it is read.
var d = new Defaults();
Console.WriteLine($"int: {d.Number}");
Console.WriteLine($"bool: {d.Flag}");
Console.WriteLine($"double: {d.Ratio}");
Console.WriteLine($"char: {(int)d.Letter}");
Console.WriteLine($"string is null: {d.Text is null}");
Console.WriteLine($"DateTime: {d.When}");
Console.WriteLine($"int?: {d.MaybeNumber}");
int[] arr = new int[3];
Console.WriteLine(string.Join(",", arr));
Console.WriteLine(default(int));
Console.WriteLine(default(string) ?? "null");
// local variables get no default value: they must be assigned before use
int local;
// Console.WriteLine(local); // error CS0165: use of unassigned local variable
local = 5;
Console.WriteLine(local);
class Defaults
{
public int Number { get; set; }
public bool Flag { get; set; }
public double Ratio { get; set; }
public char Letter { get; set; }
public string? Text { get; set; }
public DateTime When { get; set; }
public int? MaybeNumber { get; set; }
}
The program prints the default values of various types.
int local; // Console.WriteLine(local); // error CS0165 local = 5;
Reading local before assigning it is a compile-time error (CS0165).
This prevents a whole class of bugs that exist in other languages.
$ dotnet run int: 0 bool: False double: 0 char: 0 string is null: True DateTime: 1/1/0001 12:00:00 AM int?: 0,0,0 0 null 5
The default expression produces the default value of any type. The
nullable int? defaults to null, which prints as an empty
string.
C# constants
A const variable cannot change after initialization. Its value must
be known at compile time. A readonly field can be assigned only in
its declaration or in a constructor, so its value may be computed at run time.
const double Pi = 3.14159;
const string Greeting = "Hello";
Console.WriteLine($"{Greeting}, {Pi}");
Console.WriteLine(Circle.Area(2));
Console.WriteLine(Circle.Created.Year > 2000);
// Pi = 3; // error CS0131: the left-hand side of an assignment must be a variable
class Circle
{
public const double Pi = 3.14159; // compile-time constant
public static readonly DateTime Created = DateTime.Now; // set at run time, once
public static double Area(double r) => Pi * r * r;
}
We define a local constant, a class constant, and a static read-only field.
$ dotnet run Hello, 3.14159 12.56636 True
The compiler replaces every use of a const with its value. Constants
are implicitly static; we cannot write static const.
C# local variable and scope
A local variable is a variable whose scope is the block in which it is declared.
Local variables can be defined in methods, loops, try blocks, and
switch sections. The scope extends from the declaration to the end of
the block, but the name is reserved in the entire block.
Console.WriteLine(Repeat(0, "hey"));
Console.WriteLine(Repeat());
Console.WriteLine(Repeat(4));
Console.WriteLine(Repeat(5, "cau"));
string Repeat(int times = 0, string message = "")
{
int defaultTimes = 3;
string defaultMessage = "hello";
int count = times == 0 ? defaultTimes : times;
string text = string.IsNullOrEmpty(message) ? defaultMessage : message;
return string.Join(" ", Enumerable.Repeat(text, count));
}
// Console.WriteLine(count); // error CS0103: count does not exist in this scope
In the example, we define the local variables defaultTimes,
defaultMessage, count, and text. Their
validity is limited by the curly brackets of the Repeat function. The
commented-out line, which reads count outside of the function, would
produce error CS0103.
$ dotnet run hey hey hey hello hello hello hello hello hello hello cau cau cau cau cau
The next example shows nested scopes and captured variables.
int n = 10;
for (int i = 0; i < 3; i++)
{
int square = i * i; // new variable on every iteration
Console.WriteLine(square);
}
// the loop variables are out of scope here, so the names can be reused in a new block
{
int i = 100;
Console.WriteLine(i);
}
{
int inner = 5;
Console.WriteLine(inner + n);
}
// a nested scope cannot redeclare a name from an enclosing scope
// { int n = 1; } // error CS0136
var action = () =>
{
int local = n * 2; // lambdas capture n
n++;
return local;
};
Console.WriteLine(action());
Console.WriteLine(n);
The loop variables i and square exist only inside the
loop. In the C# language, a nested block cannot declare a variable with the same
name as a variable of an enclosing block (error CS0136), which is why the second
i is declared in a separate block after the loop.
var action = () =>
{
int local = n * 2;
n++;
return local;
};
A lambda expression captures the variable n, not its value.
The lambda changes the original variable, so after the call n is 11.
$ dotnet run 0 1 4 100 15 20 11
C# instance variable
An instance variable lives within an instance of a class. It ceases to exist when there are no more references to the instance and the garbage collector reclaims the object. Each instance variable is unique in each created object.
var u1 = new User { Name = "John Doe", Occupation = "gardener" };
Console.WriteLine(u1);
var u2 = new User { Name = "Roger Roe", Occupation = "accountant" };
Console.WriteLine(u2);
u2.Name = "Roger R.";
Console.WriteLine(u1.Name);
Console.WriteLine(u2.Name);
class User
{
private int visits; // a private instance field
public required string Name { get; set; }
public required string Occupation { get; set; }
public void Visit() => visits++;
public override string ToString() => $"{Name} is a(n) {Occupation}";
}
We have the User class, which has the instance variables
Name and Occupation, here exposed as properties, and a
private field visits. These variables are distinct in the two
created instances.
public required string Name { get; set; }
The required modifier forces every object initializer to set the
property, so a User cannot be created without a name. This also
satisfies the nullable reference type analysis, which would otherwise warn about a
non-nullable property that is never assigned.
$ dotnet run John Doe is a(n) gardener Roger Roe is a(n) accountant John Doe Roger R.
Changing the name of the second user leaves the first one untouched.
C# static variable
A static variable is shared among all instances of the class. Only one copy of a static member exists, regardless of how many instances of the class are created.
var counter1 = new Counter();
counter1.F();
counter1.F();
counter1.F();
var counter2 = new Counter();
counter2.F();
counter2.F();
counter2.F();
Console.WriteLine(counter1.Show());
Console.WriteLine(counter2.Show());
Console.WriteLine(Counter.Count);
class Counter
{
public static int Count; // one copy for the whole class
private int calls; // one copy per object
public void F()
{
Count++;
calls++;
}
public string Show() => $"this object: {calls}, all objects: {Count}";
}
We have a static Count variable and an instance variable
calls in the Counter class. The F method
increments both.
$ dotnet run this object: 3, all objects: 6 this object: 3, all objects: 6 6
Each object has made three calls, but the static counter was incremented by both
objects, so it reports six. A static variable is accessed through the type name,
as in Counter.Count.
C# variable - function parameters
Value parameters come into existence upon the invocation of a function to which the parameter belongs. A value parameter is initialized with a copy of the argument given in the invocation.
int r = Add(5, 6);
Console.WriteLine(r);
int a = 11;
Console.WriteLine(Add(a, 12));
Increment(a); // a copy is changed
Console.WriteLine(a);
int Add(int x, int y)
{
return x + y;
}
void Increment(int value)
{
value++;
}
In the example, we have the parameters x and y of the
Add function, and the parameter value of
Increment. They are valid only within their functions.
$ dotnet run 11 23 11
The Increment function changes its own copy, so the caller's variable
a is still 11.
C# ref, out, and in parameters
A parameter declared with the ref modifier is a reference parameter.
It does not create a new storage location; it represents the same storage
location as the variable given as the argument. The out modifier is
similar, but the function must assign the parameter, and the caller does not need
to initialize the variable. The in modifier passes a read-only
reference, which avoids copying large structures.
int x = 5;
int y = 6;
Console.WriteLine($"{x} {y}");
Change(ref x, ref y);
Console.WriteLine($"{x} {y}");
// out: the method must assign the value
if (int.TryParse("42", out int parsed))
{
Console.WriteLine(parsed);
}
Divide(17, 5, out int quotient, out int remainder);
Console.WriteLine($"{quotient} {remainder}");
// in: passed by reference, but read-only
Console.WriteLine(Sum(in x, in y));
// ref local and ref return: an alias to an array element
int[] data = [1, 2, 3];
ref int first = ref data[0];
first = 100;
Console.WriteLine(string.Join(",", data));
void Change(ref int a, ref int b)
{
a = 15;
b = 16;
}
void Divide(int a, int b, out int q, out int r)
{
q = a / b;
r = a % b;
}
int Sum(in int a, in int b) => a + b;
The example uses all three modifiers and a ref local variable.
Change(ref x, ref y);
No new variables are created in the Change function; references to the
existing x and y are passed. The ref
keyword is required in both the declaration and the call.
if (int.TryParse("42", out int parsed))
The out variable can be declared inline, in the call. This is how the
TryParse methods return their result.
ref int first = ref data[0]; first = 100;
A ref local is an alias of another variable, here of an array element.
Assigning to first changes the array.
$ dotnet run 5 6 15 16 42 3 2 31 100,2,3
C# tuples, discards, and nullable variables
Several variables can be declared and assigned at once through tuple
deconstruction. A discard, written as _, ignores a value we do not
need. Nullable types allow value types to hold null, and with
nullable reference types enabled, the compiler tracks which reference variables
may be null.
// tuple deconstruction, swap, and discards
var (name, age) = ("Lucia", 27);
Console.WriteLine($"{name} {age}");
int a = 1, b = 2;
(a, b) = (b, a);
Console.WriteLine($"{a} {b}");
var (_, years) = GetPerson();
Console.WriteLine(years);
// nullable reference and value types
string? maybe = null;
int? count = null;
Console.WriteLine(maybe?.Length ?? -1);
Console.WriteLine(count ?? 0);
count = 7;
Console.WriteLine(count.HasValue);
// null-coalescing assignment
string? title = null;
title ??= "untitled";
Console.WriteLine(title);
// valid identifiers
int _private = 1;
int café = 2;
int @class = 3; // @ lets us use a keyword as an identifier
Console.WriteLine(_private + café + @class);
(string, int) GetPerson() => ("John", 34);
The example shows more ways of declaring and using variables.
(a, b) = (b, a);
This swaps two variables without a temporary variable.
string? maybe = null; int? count = null; Console.WriteLine(maybe?.Length ?? -1);
The ? suffix says that the variable can be null. The
null-conditional operator ?. accesses a member only if the variable is
not null, and the null-coalescing operator ?? supplies a
fallback value.
title ??= "untitled";
The ??= operator assigns the value only if the variable is currently
null.
$ dotnet run Lucia 27 2 1 34 -1 0 True untitled 6
Source
Declaration statements - C# reference
In this article we have worked with variables in C#.
Author
List all C# tutorials.