During an research the purpose of this
reassignment possibility with structs I ran into following puzzle: Why it is needed to do this = default(...)
at the beginning of some struct constructor. It's actually zeroes already zeroed memory, isn't it?
See an example from .NET core:
public CancellationToken(bool canceled)
{
this = default(CancellationToken);
if (canceled)
{
this.m_source = CancellationTokenSource.InternalGetStaticSource(canceled);
}
}
A default constructor is a constructor which can be called with no arguments (either defined with an empty parameter list, or with default arguments provided for every parameter). A type with a public default constructor is DefaultConstructible.
The default constructor in Java initializes the data members of the class to their default values such as 0 for int, 0.0 for double etc. This constructor is implemented by default by the Java compiler if there is no explicit constructor implemented by the user for the class.
In both Java and C#, a "default constructor" refers to a nullary constructor that is automatically generated by the compiler if no constructors have been defined for the class. The default constructor implicitly calls the superclass's nullary constructor, then executes an empty body.
If not Java compiler provides a no-argument, default constructor on your behalf. This is a constructor initializes the variables of the class with their respective default values (i.e. null for objects, 0.0 for float and double, false for boolean, 0 for byte, short, int and, long).
It's actually zeroes already zeroed memory, isn't it?
No. When you create custom constructor for struct
, it's your responsibility to set each and every field of struct to some value.
Just default .ctor() will fill it with zeroes - and that's one of the reasons why you are not allowed to implement own default .ctor for struct in C# (while CLR technically allows it, but it's a different topic to discuss).
So technique here is to call default()
, which will create separate instance filled with zeroes, when using 'this = ' assignment will copy all fields from right to left (as it is struct), which will satisfy you need to initialize every field of struct. Then, you can do whatever you want.
In most cases it might be better (from code readability) to use something like this instead:
public MyStruct(..) : this() {
...
}
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