C# default constructor even if there is an explicit constructor

37 views Asked by At

I've defined a C# struct:

public struct Separator {
    readonly StringBuilder sb;
    readonly char ch;
    bool more;

    public void Write() {
        if (more)
            sb.Append(ch);
        more = true;
    }

    public Separator(StringBuilder sb, char ch = ',') {
        this.sb = sb;
        this.ch = ch;
    }
}

When the constructor is called, all is good. However, if I write:

var separator = new Separator();

I expected this to be a compile-time error, as it is in C++ and Java, but the C# compiler went right ahead and let me use an instance with sb left as null (which then caused a null pointer exception at runtime).

Does C# just not have the rule about default constructor only being supplied if you didn't write any explicit ones? If so, okay, I am surprised (C# usually errs more on the side of caution than C++ and Java do), but if that's just how the language works, I can live with it. But maybe there is something else I am missing?

0

There are 0 answers