Calling code before the base constructor is called #3984
Replies: 4 comments 8 replies
-
See also #3980. Yes, that solution would still leave you with a separate method, but at least it'll be scoped to the constructor and won't be visible in the rest of your class. |
Beta Was this translation helpful? Give feedback.
-
this is good but have few problem public abstract class a
{
public a(int a, int b){...}
}
public sealed class b : a
{
public b() : a(Make_A(), Make_B())
{
//rest of ctor here
}
private static int Make_A()
{
//<insert many lines of code to convert here>
}
private static int Make_B()
{
//<insert many lines of code to convert here>
}
} |
Beta Was this translation helpful? Give feedback.
-
Uhm, is there a reason this isn't a constructor for This is potentially somewhat breaking some best practices (because now you're constructing two things). Which is when you normally inject a resource you constructed externally. |
Beta Was this translation helpful? Give feedback.
-
Only that C# wasn't designed for to allow for this. It inherited the syntax from C++ which forces that the chained constructor call be the first statement. The runtime has a bit of flexibility here and does allow for code before base constructor calls, which is why you can use expressions as the arguments. From a language perspective the challenge is that this would require some kind of new syntax to express the chained constructor call. I like the suggestion of using |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
When I have some sort of a setup like this:
It is annoying to me that I need to have the MakeC method here, and I cannot just do something like:
which in my opinion, is much neater and more logical, or even something better like this (which would allow for calling multiple ctors too, which is permissible in IL code AFAIK, but maybe not particularly useful)
I think this should be a feature of C# (I prefer the 2nd version).
Is there any reason that it isn't?
Beta Was this translation helpful? Give feedback.
All reactions