default
keyword in C#?The default statement is executed if no case constant-expression value is equal to the value of expression . If there's no default statement, and no case match is found, none of the statements in the switch body get executed. There can be at most one default statement.
Definition and Usage The default keyword the default block of code in a switch statement. The default keyword specifies some code to run if there is no case match in the switch. Note: if the default keyword is used as the last statement in a switch block, it does not need a break .
Default Keyword and Defaulted Function in C++ Making a function explicitly default has advantages as it forces the compiler to generate the default implementation. And in terms of efficiency, they are better than the manually implemented functions.
The default
keyword is contextual since it has multiple usages. I am guessing that you are referring to its newer C# 2 meaning in which it returns a type's default value. For reference types this is null
and for value types this a new instance all zero'd out.
Here are some examples to demonstrate what I mean:
using System;
class Example
{
static void Main()
{
Console.WriteLine(default(Int32)); // Prints "0"
Console.WriteLine(default(Boolean)); // Prints "False"
Console.WriteLine(default(String)); // Prints nothing (because it is null)
}
}
You can use default to obtain the default value of a Generic Type
as well.
public T Foo<T>()
{
.
.
.
return default(T);
}
The most common use is with generics; while it works for "regular" types (i.e. default(string)
etc), this is quite uncommon in hand-written code.
I do, however, use this approach when doing code-generation, as it means I don't need to hard-code all the different defaults - I can just figure out the type and use default(TypeName)
in the generated code.
In generics, the classic usage is the TryGetValue
pattern:
public static bool TryGetValue(string key, out T value) {
if(canFindIt) {
value = ...;
return true;
}
value = default(T);
return false;
}
Here we have to assign a value to exit the method, but the caller shouldn't really care what it is. You can contrast this to the constructor constraint:
public static T CreateAndInit<T>() where T : ISomeInterface, new() {
T t = new T();
t.SomeMethodOnInterface();
return t;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With