The default keyword helps you get the default value of any type, especially useful when working with generic types where you don't know the exact type in advance.
0
0
Default keyword for generic types in C Sharp (C#)
Introduction
When you write a method that works with any type and need to return a default value if no specific value is given.
When you want to reset a variable of a generic type to its default state.
When you want to compare a generic type variable to its default value to check if it has been set.
When you create generic classes or methods and need a safe initial value for any type.
Syntax
C Sharp (C#)
default(T)
T is the generic type parameter.
For reference types, default(T) is null. For value types like int, it is 0. For bool, it is false.
Examples
Gets the default value for
int, which is 0.C Sharp (C#)
int defaultInt = default(int);
Gets the default value for
string, which is null.C Sharp (C#)
string defaultString = default(string);
In a generic method or class, this gets the default value for the generic type
T.C Sharp (C#)
T defaultValue = default(T);
Sample Program
This program defines a generic method ShowDefault that prints the default value of any type T. It shows how default works for different types.
C Sharp (C#)
using System; class Program { static void ShowDefault<T>() { T value = default(T); Console.WriteLine($"Default value of {typeof(T)} is: {(value == null ? "null" : value)}"); } static void Main() { ShowDefault<int>(); ShowDefault<bool>(); ShowDefault<string>(); ShowDefault<DateTime>(); } }
OutputSuccess
Important Notes
Use default to avoid errors when you don't know the type in advance.
For nullable types, default is null.
Since C# 7.1, you can also use default literal without specifying the type when the compiler can infer it.
Summary
default gives the default value for any type, useful in generic code.
For value types, default is usually zero or equivalent; for reference types, it is null.
It helps write safe and flexible generic methods and classes.