Follow

Suppose class B extends class A. In your constructor for B, you want to call the constructor for A. In :

public B(int x) {
super(x);
...
}

In :

public B(int x) : base(x) {
...
}

Why does C# introduce special syntax (and overload the colon) for this?

@peterdrake If I had to guess the reason is so that the fact that the call is first is more explicit in the c# code. In Java I could write this:

public B(int x) {
y = y + 7;
super(x);
}

But that is invalid code (even though it 'looks' fine), in the c# syntax I can't even write it invalidly in the first place.

@bdavisx I see the reasoning, but of course the compiler or IDE would catch that. Being reminded of such an error seems much less of a burden than having to know to write (or read) special syntax just for this one purpose.

Maybe after my upcoming year of immersion in C# and Unity all this will feel natural, but right now it seems like the the answer to every question is an additional mechanism.

@peterdrake @bdavisx but the IDE should also pre-fill that for you as soon as type ctor Ctrl+Space so it shouldn't be an issue either way.

Sign in to participate in the conversation
CleverLibre Social

CleverLibre Social is an inclusive social instance for open discussion, learning, and community.
All cultures welcome.
Hate speech and harassment strictly forbidden.