Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#8 what does "default!" do on generic types?

Just playing around with C# 8.0 Beta and updating some of my code to use nullable reference types.

I have a node style class for a Trie implementation. Each node has a value of type T. The constructor for the root node does not need a value, so I was setting this to default.

Here's a short version:

public class Trie<T>
{
    public readonly bool caseSensitive;
    public readonly char? letter;
    public readonly Dictionary<char, Trie<T>> children;
    public readonly Trie<T>? parent;
    public readonly int depth;
    public bool completesString;
    public T value;

    public Trie(bool caseSensitive = false)
    {
        this.letter = null;
        this.depth = 0;
        this.parent = null;
        this.children = new Dictionary<char, Trie<T>>();
        this.completesString = false;
        this.caseSensitive = caseSensitive;
        this.value = default;
    }
}

if the last line of the ctor is changed to

   this.value = default!;

as I saw in a different question here, then it compiles just fine. But I don't understand what the ! is doing here, and it's pretty hard to google, since google seems to ignore punctuation in most cases.

What does default! do?

like image 256
craig Avatar asked Sep 04 '26 03:09

craig


1 Answers

The nullable reference types use static flow analysis to figure out if you have a possible null value (thus issuing a warning the variable is being assigned a null value).

The ! is used to allow the developer to suppress the warning generated. Essentially overriding the compiler.

like image 133
Adam Carr Avatar answered Sep 06 '26 18:09

Adam Carr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!