[Proposal] Reduce boilerplate assignments in primary constructors with better default assignments #8083
Replies: 2 comments 2 replies
-
Why not pass
I'm not sure primary constructors are meant to be able to recreate every single use case of normal, ordinary constructors. Increasing the amount of logic which can be crammed into the parameter list of a function (here, a constructor) doesn't feel like a great idea to me. |
Beta Was this translation helpful? Give feedback.
-
This should just work: public class TestClass(ILogger<TestClass>? logger = NullLogger<TestClass>.Instance)
{
} Then you can just omit the value but if you would pass null, well, it could fail so I guess that's another case but then in that case I'd suggest the following as opposed to public class TestClass(ILogger<TestClass>? logger =?? NullLogger<TestClass>.Instance)
{
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
The new primary constructors are neat but for me they lack some significant abilities to actually save you time and space writing your classes. Typical scenario in ASP.NET apps that I always have is a class like this:
Why null? Well, this makes it easier for testing since you can just pass null for the logger and don't even have to waste time mocking the interface (even with an empty mock). So with that scheme you basically eliminate the need to test the logging while also ensuring that your code (in case it's a library) is opt-in friendly for logging in case the source app doesn't even have logging enabled / injected.
But using this approach the primary constructors get kind of useless and verbose. Not only is the
logger
parameter now exposed in the whole file but also it's possibly null. So now IntelliSense always shows bothlogger
and_logger
which is annoying and confusing and prone to errors.What I would suggest would be reusing the
value
keyword and extend the syntax so it's possible to do a default assignment like this:This would save the headaches I just mentioned and only emits one parameter which is correctly annotated as "not null". In this scenario the
value
keyword can be interpreted as "input parameter". What the compiler would emit is basically what the "current" manual code would look like. Since this would be just some syntactic sugar, it should be no problem that the part after the null-coalescing operator is not constant.I haven't checked what IL the primary constructors actually emit but I guess it would be just some fields and a regular constructor. So I assume this should be compatible.
What's your thoughts?
Beta Was this translation helpful? Give feedback.
All reactions