default OperatorUse the default operator, which returns the default value of a type.
This page was last reviewed on Dec 8, 2022.
Default. Every reference and value type has a default value. This value is returned by the default(Type) expression. Default is most useful for writing generic classes.
Shows an int array
Notes, generic method. In a generic method, sometimes we need to return a value that is not yet initialized—we can use default() for this.
First example. We look at 4 uses of the default operator. The 4 types we apply the default expression to are the StringBuilder, int, bool and Program types.
Int, uint
Finally The values that were assigned are printed to the screen. The null value is printed as a blank line.
Shows an int array
using System; using System.Text; class Program { static void Main() { // Acquire the default values for these types and assign to a variable. StringBuilder variable1 = default(StringBuilder); int variable2 = default(int); bool variable3 = default(bool); Program variable4 = default(Program); // Write the values. Console.WriteLine(variable1); // Null Console.WriteLine(variable2); // 0 Console.WriteLine(variable3); // False Console.WriteLine(variable4); // Null } }
(Blank) 0 False (Blank)
Default, generic class. Here we have the generic class Test, which requires a class parameter with a public parameterless constructor.
Generic Class, Method
GetOrDefault This method returns a new instance of the type parameter. If the size field is 0, it returns the default value.
using System; using System.Text; class Test<T> where T : class, new() { int _size; public T GetOrDefault() { // Use default in a generic class method. return _size == 0 ? default(T) : new T(); } } class Program { static void Main() { Test<StringBuilder> test = new Test<StringBuilder>(); Console.WriteLine(test.GetOrDefault() == null); } }
A discussion. The default value expression is implemented using static analysis. This means the default expressions are evaluated at compile-time, resulting in no performance loss.
So No reflection to the type system or metadata relational database is used at runtime.
And Unlike with typeof expressions, caching the default expression would have no benefit.
Typeof, nameof
A summary. We looked at the default value expression. By understanding the usage of the default value expression, we can better understand the type system.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
No updates found for this page.
© 2007-2023 Sam Allen.