✅ What is a primary constructor in C#
Hello guys, was just reading a bit about primary constructors. My question is, primary constructors is just a "fancy" way to write less code instead of declaring a whole constructor? Or are there any reasons why we would use primary constructors?
16 Replies
Yes, primary constructors are literally just a simpler way to write normal constructors.
These two are literally equivalent
If the constructor is public and you don't need any kind of functionality in the constructor besides initializing data, then a primary constructor is the same.
yep I see
-# There are some slight nuances, but those are quite fringe.
Now, mind you, what the primary ctor generates can differ
Depending on where you capture those params
yeah the idea of backing field, etc ?
But most of the time it doesn't really matter
ye
oh yeah, right, you can reference the parameters from the primary constructor elsewhere in the class
eg. you can do this
yeah I see, yeah I see, hmm, consider the code:
when we use primary constructors, like here:
the syntax is to set the variable "name" used in the primary constructors to the property "Name"?
Reverse, the property
Name
is set to the parameter name
yeah sorry
You can always use Sharplab to see what gets generated
yeah I see
Mind you again that primary constructors in records actually declare properties, which primary constructors in normal classes do not
And that nobody really writes
record class
when you can use just record
😛in
record L(string Z);
, Z
will become a property, but in class L(string z);
you'll get an empty class with just a constructor
It's somewhat odd, but you don't need to worry about it too much unless you already know what records are.just learning about that :c
yep, I guess if I have some doubts, will just stick with sharplab to clearly see what's happening
But I have an overview now, thanks guys 👍