The Default Keyword in C#
Published: Saturday, May 14, 2022
Updated: Tuesday, May 17, 2022
Greetings, friends! In C#, you can use the default
keyword to produce default values for various types. For example, suppose we want to use the default operator to create a default value for the type, int
(integer).
csharp
using System;
public class Program
{
public static void Main()
{
int defaultValue = default(int);
Console.WriteLine(defaultValue);
// OUTPUT: 0
}
}
You can try out this code by copying and pasting it to .NET Fiddle.
By using the default
keyword as an operator and passing in a type, we can get the default value for that type. The table shown on Microsoft's default values page lists the default value for each type.
You can also use a default literal to initialize a variable with the default value of its type.
csharp
using System;
public class Program
{
public static void Main()
{
int defaultValue = default;
Console.WriteLine(defaultValue);
// OUTPUT: 0
}
}
You can even set the parameters of a function to a default
literal.
csharp
using System;
public class Program
{
public static void Main()
{
int someValue = MyFunc();
Console.WriteLine(someValue);
// OUTPUT: 3
int someValue2 = MyFunc(4);
Console.WriteLine(someValue2);
// OUTPUT: 7
}
private static int MyFunc(int a = default)
{
// If no value is passed, return 0 + 3 = 3
return a + 3;
}
}