Any way to inherit base abstract class' constructor?
Pretty new to C#. I've got this goofy code:
In python, if you inherit from a class that defines a constructor, it will be inherited, and when creating an instance of that subclass, that inherited constructor is called. I know, its just a single (a bit long) line, but is there something similar in C#? (or, at least, a way to make that line shorter...)
10 Replies
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/base is what you're looking for I believe
base keyword - C# Reference - C#
Learn about the base keyword, which is used to access members of the base class from within a derived class in C#.
well, if using
base
is the only way, then i guess i can only use that long ahh line 😭Aye, there's no implicit way to call the base constructor. You'll need to define it.
i just dont like the fact that i have to basically copypaste the thing into each subclass
thanks for your answer
Then perhaps your derived classes are redudant.
If they don't need any modifications.
here's what i've got so far
(and some Instructions will have their own fields)
I obviously don't have the entire code context here, but:
My intuition says instructions could be an interface and you could pass dependencies from method arguments.
I second using an interface, but with primary ctors, it's not that bad.
(if you really want the not-null check you can add them inline with
?? throw new ArgumentNullException()
)in general the solution for this issue is required properties
they were added specifically to circumvent repeated constructor boilerplate in deep inheritance trees
then:
i am not really a fan of this design, though, in general
the fact that the
PushZero
class doesn't define any additional state suggests, the 3 arguments should just be parameters to Callback
that avoids all the boilerplate, in generalthere were originally protected, but you can do that with required properties, though some think it weird.