Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What the purpose of this = default(...) in struct constructor?

Tags:

c#

.net

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);
    }
}
like image 308
Eugene D. Gubenkov Avatar asked Feb 20 '14 07:02

Eugene D. Gubenkov


People also ask

What is the default constructor of a struct?

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.

What is the purpose of a default constructor?

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.

What is the default statement in constructor?

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.

What is the advantage of default constructor?

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).


1 Answers

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() {
...
}
like image 153
Lanorkin Avatar answered Nov 15 '22 07:11

Lanorkin