✅ Default operator
Can somebody give me ELI5 explanation for the necessity of the
default
operator? I'm under the impression everything that's declared but not initialized is automatically given a default value, typically 0
or null
depending on the type. When would something not get an implicit default value? (Assuming that's why the default
operator exists)11 Replies
locals are never given a value implicitly
Windows10CE#8553
REPL Result: Failure
Exception: CompilationErrorException
Compile: 507.910ms | Execution: 0.000ms | React with ❌ to remove this embed.
you can use
= default;
to say you want the default value
which might matter if you have say, a generic method, because you won't know what the default is ahead of timeWindows10CE#8553
REPL Result: Success
Result: int
Compile: 459.078ms | Execution: 33.766ms | React with ❌ to remove this embed.
So for locals that makes sense, but I was under the impression fields always got a default value. I'm seeing this in the language extension library though:
wouldn't bottom always get a default value upon instantiation? Regardless of whether
A
was a class, struct, or primitive type?yes
they're just being explicit
While it would have default value, analyzer could yell at you for not assigning anything. Especially for static readonly it’s better to be explicit
For the specific reason of why
default
exists, and we don't just tell people to use null
or new MyStructType()
, consider generics:
Was this issue resolved? If so, run
/close
- otherwise I will mark this as stale and this post will be archived until there is new activity.That generic local makes things clear. Thanks everyone.