Skip to main content

How to Use the default Literal in C#

· 9 min read
Jagdish Kumawat
Founder @ Dewiride

Write default where C# already knows the type, as in int score = default; or a parameter Point square = default, and you get that type's default value: 0, false, null, or a struct with every field at its default. You don't name the type: the compiler takes it from where default stands.

Microsoft's reference: You can use the default literal to produce the default value of a type when the compiler can infer the expression type. The default literal expression produces the same value as the default(T) expression where T is the inferred type.

Which value you get depends on the type. The reference's table of default values gives null for any reference type, 0 (zero) for the built-in numeric types and false for bool. For a struct, it's The value produced by setting all value-type fields to their default values and all reference-type fields to null.

Syntax​

Syntax
<Type> <variable> = default;
<ReturnType> <Method>(<Type> <parameter> = default)
<Method>(default);
return default;
PartWhat it is
defaultThe default value of the type C# infers from where it stands
<Type> <variable> = default;A variable that starts at the default value of <Type>
<Type> <parameter> = defaultAn optional parameter: a call that leaves it out gets the default value of <Type>
<Method>(default)An argument: the default value of that parameter's type
return default;The default value of the method's return type

These are the four places the reference lists: a variable's assignment or initialization, an optional parameter's default value, a method call's argument, and a return statement or expression-bodied member. Where nothing gives a type, name it with the default operator, default(<Type>).

The Example​

A console app called DefaultLiteral sets up a board game. It starts four variables at default (a score, a game-over flag, a winner and a starting square), then places tokens with a method whose square parameter defaults to default.

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 DefaultLiteral
cd DefaultLiteral
Output
The template "Console App" was created successfully.

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

dotnet new console -n DefaultLiteral creates a folder named DefaultLiteral 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 DefaultLiteral.csproj in Visual Studio.

Step 2: Write the Code​

Replace everything in Program.cs. First the variables:

Program.cs (the variables)
// The default literal gives each variable the default value of its type.
int score = default;
bool gameOver = default;
string? winner = default;
Point start = default;

Console.WriteLine($"score: {score}");
Console.WriteLine($"gameOver: {gameOver}");
Console.WriteLine($"winner: {winner ?? "null"}");
Console.WriteLine($"start: {start}");

Each default takes its type from the variable it starts: an int, a bool, a string? and a Point. winner ?? "null" prints the word null when winner is null.

Then the calls:

Program.cs (the calls)
// A call can leave out a parameter whose default value is default.
PlaceToken("Ana");
PlaceToken("Ben", new Point(2, 3));

// default also works as an argument. Here it means a default Point.
PlaceToken("Cara", default);

Ana's call leaves the square out, Ben's passes one, and Cara's passes default, which C# turns into a Point because that's the parameter's type.

Last, the method and the struct:

Program.cs (the method and the struct)
static void PlaceToken(string player, Point square = default)
{
Console.WriteLine($"{player} places a token on {square}");
}

// A struct's default value has every field at its own default.
record struct Point(int X, int Y);

Point square = default makes square optional. Point is a record struct: a struct with two int properties, X and Y, that prints its name and their values.

Step 3: Run It​

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

Terminal
dotnet run
Output
score: 0
gameOver: False
winner: null
start: Point { X = 0, Y = 0 }
Ana places a token on Point { X = 0, Y = 0 }
Ben places a token on Point { X = 2, Y = 3 }
Cara places a token on Point { X = 0, Y = 0 }

macOS-style terminal window titled Terminal — DefaultLiteral showing dotnet run printing score: 0, gameOver: False, winner: null and a start Point with X and Y at 0, then Ana and Cara placing a token on the Point with X and Y at 0 and Ben on the Point with X 2 and Y 3

Each default gave the value the reference's table lists for its type: 0 for the int, False for the bool, null for the string?, and a Point with X and Y at 0. Ana's call left the square out and got that same default Point, and so did Cara's default argument. Ben's new Point(2, 3) replaced the default.

The Complete File​

macOS-style code window titled Program.cs — DefaultLiteral showing an int score, a bool gameOver, a nullable string winner and a Point start all set to default, the lines that print them, three PlaceToken calls with no square, a new Point and default, the PlaceToken method whose Point square parameter defaults to default, and the Point record struct

Program.cs
// The default literal gives each variable the default value of its type.
int score = default;
bool gameOver = default;
string? winner = default;
Point start = default;

Console.WriteLine($"score: {score}");
Console.WriteLine($"gameOver: {gameOver}");
Console.WriteLine($"winner: {winner ?? "null"}");
Console.WriteLine($"start: {start}");

// A call can leave out a parameter whose default value is default.
PlaceToken("Ana");
PlaceToken("Ben", new Point(2, 3));

// default also works as an argument. Here it means a default Point.
PlaceToken("Cara", default);

static void PlaceToken(string player, Point square = default)
{
Console.WriteLine($"{player} places a token on {square}");
}

// A struct's default value has every field at its own default.
record struct Point(int X, int Y);

Why a Struct Parameter Uses = default​

A parameter's default value has to be known when the code compiles. The methods guide lists three kinds of value: a constant, such as a literal string or number; default(SomeType) or the default literal; and new ValType() for a value type. A static field isn't on that list, so a Point.Origin field as the default didn't build:

A static field as the default
// Point.Origin is a static readonly field, not a constant.
static void PlaceToken(string player, Point square = Point.Origin)
{
Console.WriteLine($"{player} places a token on {square}");
}

record struct Point(int X, int Y)
{
public static readonly Point Origin = new(0, 0);
}

The build failed with error CS1736: Default parameter value for 'square' must be a compile-time constant. The reference for CS1736 explains why: What a value may be when the method is eventually invoked cannot be pre-determined at declaration-time unless that value is constant at compile-time. Point square = default is known when the code compiles, and it gives the same Point with X and Y at 0.

Common Mistakes​

MistakeWhat happensDo this instead
var total = default;error CS8716: There is no target type for the default literal. With var, nothing tells C# which type's default to giveGive the variable a type, int total = default;, or name it with the operator, var count = default(int);: both printed 0
A static field or property as a parameter's default, such as Point square = Point.Originerror CS1736: Default parameter value for 'square' must be a compile-time constantWrite Point square = default
Expecting default to give an empty stringstring? winner = default; is null: the build warned warning CS8602: Dereference of a possibly null reference., and winner.Length threw NullReferenceException: Object reference not set to an instance of an object.Use "" for an empty string: its Length was 0

FAQ​

What does CancellationToken cancellationToken = default mean?​

It makes the token optional. A caller that leaves it out gets an empty token, which is never canceled: for a default token, a check printed Equals CancellationToken.None: True and CanBeCanceled: False. The reference for CancellationToken.None: You can also use the C# default(CancellationToken) statement to create an empty cancellation token. Methods write = default because = CancellationToken.None doesn't build. It's a property, and the check failed with error CS1736: Default parameter value for 'token' must be a compile-time constant.

Is default the same as new() for a struct?​

Not when the struct has a parameterless constructor of its own. For a Size whose constructor sets both sides to 10, new Size() printed Size { Width = 10, Height = 10 } and default printed Size { Width = 0, Height = 0 }. The reference: To get the default value of a type, use the default operator or the default literal. As a parameter's default, Size size = new Size() failed with CS1736 too.

Conclusion​

Write default where C# already knows the type: a variable with a type, a parameter, an argument or a return. It gives 0, false, null, or a struct with every field at its default. It's the way to make a struct parameter optional, as in Point square = default or CancellationToken cancellationToken = default, and where nothing gives a type, write default(<Type>).

Additional Resources​