class constructor in c#
My editor wants to convert the following code
to this
is this the recommended way to write the constructor in c#? And do I still need the
private readonly DiscordClient discord = discord;
part or does that get automatically assigned.16 Replies
it depends on what you're doing, those are called primary constructors
i'd give this a read: https://learn.microsoft.com/en-us/dotnet/csharp/whats-new/tutorials/primary-constructors#primary-constructors
Declare and use C# primary constructors in classes and structs
Learn how and when to declare primary constructors in your class and struct types. Primary constructors provide concise syntax to declare constructor parameters available anywhere in your type.
If you don't use the parameter anywhere, it just gets discarded basically
If you use it, it gets assigned to a field
Not a readonly one, alas
Not yet at least
So its basically the same as function parameters but for a class and you'd still need
private readonly DiscordClient discord = discord;
to access it like this.discord
. thanks!See what the compiler generates
It is better to use when you are doing only DI. It make it looks more cleaner.
Stick with your original constructor imo. Personally I stay away from primary constructors until they fix any obvious "flaws" in its design and polish it more. I don't know why they released it when the design was incomplete (because they couldn't decide what to do)
The only thing they need to be complete, IMHO, is just a possible
readonly
on the parametersyup
It's funny because there was a convo about this not too long ago
Primary constructors actually expose the parameters you pass on class level and these are completely mutable. I don't know how much this affects you since it might or might not use the field you declared here
For some reason this is not explicitly mentioned, but it's a pretty big smell that comes with primary constructors that is not obvious, yet the editor acts like it's a more conventiont alternative that doesn't introduce different semanthics
I would say it is not the recommented way and you should stick to the first approach because of this. You should check if the editor actually uses your field and it doesn't default to the parameter. I have suspicion it would do this, actually.
@Moebytes
I'll just casually plug myself here
https://www.nuget.org/packages/Anton.AutoConstructor.SourceGenerator
Anton.AutoConstructor.SourceGenerator 1.0.3
Package Description
Idk what you are implying with this
not in answer to you
I understand that. I don't see what you are implying with this in general
Is this supposed to be an alternative? I don't get it
Repo doesn't explain it either
this thing makes a constructor for all private readonly fields
actually all private fields iirc