Given the following code:
public struct Foo
{
public Foo(int bar, int baz) : this()
{
Bar = bar; // Err 1, 2
Baz = baz; // Err 3
}
public int Bar { get; private set; }
public int Baz { get; private set; }
}
What does : this()
actually do? There is no default constructor, so what is it calling? Without this addendum, the whole thing crashes with errors.
Error 1 The 'this' object cannot be used before all of its fields are assigned to Error 2 Backing field for automatically implemented property 'Foo.Bar' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer. Error 3 Backing field for automatically implemented property 'Foo.Baz' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.
A default constructor is a constructor that either has no parameters, or if it has parameters, all the parameters have default values. If no user-defined constructor exists for a class A and one is needed, the compiler implicitly declares a default parameterless constructor A::A() .
No default constructor is created for a class that has any constant or reference type members.
When you use new[] each element is initialized by the default constructor except when the type is a built-in type. Built-in types are left unitialized by default.
Precisely. Class A has a default constructor because you're not providing any constructor for the class. The compiler, therefore, automatically provides a no-argument, default constructor.
So why is a struct constructor with no arguments not permitted in C#? This is because structs already contain a default constructor which has no arguments. Keep in mind that this default constructor is part of the .Net framework, therefore it is not visible in our code. The sole purpose of the default constructor is to assign default values to its members.
Basically, all structs have a default constructor already. The situation would be different with a class.
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