Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is happening here? How can I call the default constructor when there is none?

Tags:

c#

struct

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.
like image 364
Matthew Scharley Avatar asked Sep 20 '09 00:09

Matthew Scharley


People also ask

What happens if there is no default constructor?

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

Can a class have no default constructor?

No default constructor is created for a class that has any constant or reference type members.

Does new call default constructor?

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.

Which of the following classes have a default constructor?

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.


1 Answers

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.

like image 117
George Mauer Avatar answered Oct 19 '22 05:10

George Mauer