What is the use of the `default` keyword in C #?

  • What is the use of the default keyword in C #?
  • Is it part of C # 3.0?
+64
c #
Nov 13 '09 at 5:43
source share
6 answers

The default keyword is contextual because it has several uses. I assume that you mean its new C # 2 value, in which it returns the default value of the type. For reference types, this is null , and for value types, this is a new instance, all zero.

Here are a few 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) } } 
+82
Nov 13 '09 at 5:45
source share

You can use the default value to get the Generic Type default value.

 public T Foo<T>() { . . . return default(T); } 
+75
Nov 13 '09 at 6:02
source share

The most common use with generics ; while it works for β€œregular” types (ie default(string) , etc.), this is rather unusual in handwritten code.

However, I use this approach when creating code, as it means I don’t need to hardcode all the different default values ​​- I can just figure out the type and use default(TypeName) in the generated code.

In generics, 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 does not care what it is anyway. You can compare this with a constructor constraint:

 public static T CreateAndInit<T>() where T : ISomeInterface, new() { T t = new T(); t.SomeMethodOnInterface(); return t; } 
+32
Nov 13 '09 at 6:19 06:19
source share

The default keyword has different semantics depending on the context of use.

The first use is made in the context of the switch statement, available with C # 1.0:
http://msdn.microsoft.com/en-us/library/06tc147t(VS.80).aspx

The second use is used in the generics context when initializing an instance of a typical type, available with C # 2.0:
http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx

+11
Nov 13 '09 at 5:46
source share

The "default" keyword (except for the switch key) helps you initialize an instance of an object, such as a class, list, and other types. It is used because of its universal property, where it allows you to assign default values ​​to types, when you do not know its value as an advanced way to avoid errors in your future (future) code.

+3
Apr 30 '14 at 8:58
source share

Repeating and emphasizing it, use it in generics and not only in code generation.

If you need to initialize by default (already suspiciously smelly in my book), be clear. Just do it.

0
May 15, '19 at 21:37
source share



All Articles