4 ms·
This is why I prefer the way C# did this: class Base { public int Count { get; set; } = 0; public Base(int counter) { Coun
by jeroenhd 4y ago
This is why I prefer the way C# did this:
class Base {
public int Count { get; set; } = 0;
public Base(int counter) {
Count = counter;
}
}
class Sub : Base {
public Sub(int number) : base(number) {
System.Console.WriteLine($"This is the sub class constructor with {number} as an argument");
}
public Sub() : this(123) {
System.Console.WriteLine("This is the sub class constructor with no arguments");
}
}
Rather than being a magical function call at a magical position, the call to the super constructor is part of a special bit of syntax that explicitly tells you what kind of call is being done. You can't call any method at that point of the program, you have to call a constructor by its special reference.
It also makes the reason why you can do `super(fn1(), fn2())` but not extract those two calls to variables; these calls are considered to be part of a different part of the execution flow than the rest of the constructor. A simple `base()` can be left out, of course; it only matters in cases where you need a specific super constructor.
- vbezhenar 4y agoI don't see how is that convenient? Java approach will be trivially extended with this JEP and this restriction will be lifted. C# approach probably will never be improved so it'll never be convenient to use.
- ziml77 4y agoIt's not convenient, but it's clear. I would love something akin to this JEP in C#, but I'd want it in a way that makes it very clear that you're executing code prior to the base class' fields being initialized. Something along this lines of this public Foo(int bar) { prector { var baz = bar * bar; base(baz); } ctor { // Foo's constructor code } }
- int_19h 4y agoSince this and base are both keywords, and since () is not overloadable in C#, it adopt Java-like syntax for such calls without breaking backwards compatibility if it ever wants to do the same thing Java did.
- cesarb 4y agoThat's also the way C++ does it, with a very similar syntax (which means C# probably got it from C++).
- jeroenhd 4y agoVery likely. C#/Java and C++ are very different languages in their behaviours and purooses, though, so I thought I'd reference the most comparable alternative.