Primary Constructors in C# 12 Explained!

  Рет қаралды 23,549

James Montemagno

James Montemagno

Күн бұрын

The first previews of C# 12 are here and one of my favorite features, which is soon to be your favorite feature is primary constructors! But, what are they? Why do you need them? How do they work? I break down all of this with a practical real world example as to why they are absolutely amazing and you will use them in every single app.
Links:
Docs - learn.microsoft.com/dotnet/cs...
Blog - devblogs.microsoft.com/dotnet...
Code - github.com/jamesmontemagno/Aw...
Chapters:
00:00 - Intro
00:35 - What are C# constructors
02:30 - Enabling C# 12 and using primary constructors
06:35 - Real world primary constructors and dependency injection
08:35 - Wrap-up
Join this channel to get access to perks:
/ @jamesmontemagno
👕 Buy some swag! - jamesmontemagno.myspreadshop....
☕️ Buy me a coffee - www.buymeacoffee.com/jamesmon...
Follow:
👨‍💻 GitHub: github.com/jamesmontemagno
🦜 Twitter: / jamesmontemagno
📄 Website: www.montemagno.com
📰 Newsletter: newsletter.montemagno.com/
Disclaimer: This channel, videos, and streams are created in my spare time and are a product of me... James Montemagno! They are NOT officially affiliated or endorsed by Microsoft (my employer) in any way. Opinions and views are my own.
What is on my hat? It is the CLE clothing logo because I am from Cleveland! Checkout their awesome CLE merch: cleclothingco.myshopify.com/
What is that art on my wall? It is an original piece from the French street artist Gregos of La Butte Montmartre: / bcez1onhiqx
My Setup:
📷 Canon M50 Mark II - amzn.to/3P8R7lp
💡 Nanoleaf Elements Lights - amzn.to/3umwJVW
🎙 Blue Spark Microphone - amzn.to/3qgtYkq
🎙 Blue Pop Filter - amzn.to/3jEWM3r
🤳 Rode Microphone Arm - amzn.to/2Z68AlE
🎧 Sony MDR7306 Headphones - amzn.to/372jxta
📲 Stream Deck - amzn.to/373Uk1n
🖱 MX Master 2S Mouse - amzn.to/3d7J2gj
⌨️ Tecware Phantom Keyboard - amzn.to/3aUP4y9
#dotnet #csharp #visualstudio #dotnetmaui #aspnetcore #csharp12 #dotnet8

Пікірлер: 67
@Kokujou5
@Kokujou5 Жыл бұрын
finally... no longer triplicated code when dependency injection... it's a dream come true. it's so frustrating, first you need them in the constructor, then inside the constructors bvody and secondy you need them as private readonly properties inside your case. triplicated code. i was so close to switching all my classes to records just because it was so annoying but now it's finally coming to classes! now i'm happy
@ignispurgatorius5297
@ignispurgatorius5297 Жыл бұрын
I don't see myself having much use for the example around the logger, because usually that would just mean I have to pass more stuff that I might not need in most cases, so the use case feels a bit forced there. But I can definitely see the use case around having a primary constructor for myself when declaring small classes that are mostly used to shovel data between interfaces. Those will definitely look neater that way.
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Yeah I wanted to try to describe the actual feature first before showing it in an app like I did with monkey finder with DI systems in place which is the real win IMHO
@mwetzel0
@mwetzel0 Жыл бұрын
I'd take robustness and readability over saving lines of code. But, if this makes (some) code more robust and readable, than I'm all for it. I'm not sure I'll personally use the feature because I see too many cases where it's detrimental (like giving up parameter checking) and I'd rather my code be consistent (versus some using primary constructors and some not). I don't think allowing to create a Person with, say, a null name or a whitespace-only name, qualifies as robust. I'd prefer to throw an exception at construction rather than have some hard to track down condition where a bogus property caused a bug elsewhere in time and code.
@nayanchoudhary4353
@nayanchoudhary4353 Жыл бұрын
Conditional attributes should be able to help there. The only thing left would be instantiation honouring the attributes.
@nayanchoudhary4353
@nayanchoudhary4353 Жыл бұрын
Or, use a factory or builder
@aathifmahir
@aathifmahir Жыл бұрын
It would be great, if the c# team adds an option to make fields readonly by using the ReadOnly Keyword in the Primary Ctor
@obinnaokafor6252
@obinnaokafor6252 Жыл бұрын
It is being discussed and will be a needed option for Primary Constructor.
@chezchezchezchez
@chezchezchezchez Жыл бұрын
Can’t you just read from it only, and not write to it? 😂
@samuelmbah8789
@samuelmbah8789 Жыл бұрын
Nice video James. For someone who's written C# for less than a year, this feature looks cool to me 😄. I'll try it out
@waleedbensumaidea3947
@waleedbensumaidea3947 Жыл бұрын
Thank you so much James🌹. This is very helpful
@grumpydeveloper69
@grumpydeveloper69 Жыл бұрын
I see a benefit for structs and records where the parameters are the data being stored. But, what about constructors that have move than just assignments, and have calls to say a private initialisation method. That is not compatible with primary constructors right?
@Sindrijo
@Sindrijo Жыл бұрын
Does this mean we also get expanded generic constraints for constructor signatures? Before you could only constrain a generic to have a default constructor with no params e.g. SomeClass where T : new()
@ahmad.mozaffar
@ahmad.mozaffar Жыл бұрын
Thanks
@ryanye6938
@ryanye6938 Жыл бұрын
dude you gonna loooooove typescript
@WhiteCapix
@WhiteCapix Жыл бұрын
To be honest looks neat, but when you replaced the MonkeysViewModel with the primary constructor we don't have any longer the whole code on the file in front of us, we need to scroll sideways, which for me is not super. We could get some line breaks and still be fine, I would say.
@philippelhaus
@philippelhaus Жыл бұрын
Useful
@stephenmiller4948
@stephenmiller4948 Жыл бұрын
This is pretty cool, James! But… How does this work with DI? The DI container had to have been getting the class instantiation signature from the constructor. Does this require a newer version of the container?
@NiamaImia
@NiamaImia Жыл бұрын
Guess it still converts into constructor and can be obtained from class metadata with no difference, so nothing changes for DI
@JamesMontemagno
@JamesMontemagno Жыл бұрын
It works exactly the same today… it’s just a constructor :)
@HOSTRASOKYRA
@HOSTRASOKYRA Жыл бұрын
When will they finally add a constructor method, without a class name?
@mtranchi
@mtranchi Жыл бұрын
like it!
@krccmsitp2884
@krccmsitp2884 Жыл бұрын
I'm indecisive whether I like it and will use it, or not. What bothers me mostly is the different behavior to records for the same syntax.
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Yeah, compatibility has its limitations. I haven’t really moved anything to records so for me I live this where it makes sense in my classes.
@hj.0301
@hj.0301 Жыл бұрын
does it work with mapster's MapToConstructor?
@MohammadNikravan
@MohammadNikravan 6 ай бұрын
Assigning the primary constructor to a fullset property results in having two fields in your class - one for the field and one for the primary constructor. Unfortunately, we can't make the generated field as read-only in the primary constructor. If we assign parameter to a property it might cause the object to consume double the memory or at least bug prone as we have to make sure which one is used in the class. If you bypass the primary constructor to the parent, the field will exist in derived class too! This feature can be quite confusing, and I wish there was an option to disable it completely to prevent our team from using it.
@JamesMontemagno
@JamesMontemagno 6 ай бұрын
the paramter isn't a field... you can't access via "this." for example. If you want something to be read only you would want to make it read only field..... it is a constructor just like any other constructor
@gds03_
@gds03_ Жыл бұрын
what about the underscore convention for variables, specially private ones? defining a area of variables with _ to me helps a lot!
@JamesMontemagno
@JamesMontemagno Жыл бұрын
You can name them whatever you would like :)
@gregdennis6094
@gregdennis6094 Жыл бұрын
@@JamesMontemagno but then you have ctor params with underscores. Params don't have underscores by that convention.
@dotnetdevni
@dotnetdevni Жыл бұрын
Its def a game changer but did you no about the = null trick on your interfaces I didnt until a more senior then myself pointed it out.
@dmitrymezinov9238
@dmitrymezinov9238 Жыл бұрын
hmm... interesting feature, but where to check constructor params (for null, as example) and throw exceptions if necessary? isn't that common practice to do such in constructors?
@JamesMontemagno
@JamesMontemagno Жыл бұрын
I think nowadays you would just turn on null ability and mark things that can and can’t be null. Or check when you are using things in a method.
@scotty3024
@scotty3024 Жыл бұрын
C# is becoming more like Kotlin every day
@JamesMontemagno
@JamesMontemagno Жыл бұрын
I feel like there is a lot of cross over between languages and that is a good thing IMHO
@NemanjaSimovic
@NemanjaSimovic Жыл бұрын
Looks like you missed to say that primary constructor creates private field with the same name as its parameter. Nice video thou. Thanks.
@kolesplace
@kolesplace Жыл бұрын
I love these new features. If I'm hopeful my employer will adopt C# 12 by 2030 😂😂
@JackLyons00
@JackLyons00 Жыл бұрын
I feel your pain
@eriknyk2k
@eriknyk2k Жыл бұрын
I can see that it's borrowed from kotlin and I love it
@JamesMontemagno
@JamesMontemagno Жыл бұрын
🤣
@damiank6566
@damiank6566 5 ай бұрын
you dont have to add "?" to strings - they are reference types and are nullable anyway
@Eirenarch
@Eirenarch Жыл бұрын
The savings are not worth it the insane scoping rules. i'd rather have them port the records primary constructors to classes so at least they can be used to declare properties
@JamesMontemagno
@JamesMontemagno Жыл бұрын
The problem I think is records are immutable and doing the same for classes would break a bunch of things. They review all proposals and implementations in the open so provide the feedback on GitHub!
@Eirenarch
@Eirenarch Жыл бұрын
@@JamesMontemagno I've done so, as have hundreds of other people who dislike the proposal
@MartinMaat
@MartinMaat Жыл бұрын
So first they introduced multiple property styles which was undesirable and stupid (as if anyone would want their language to facilitate mixing different styles that do the exact same thing, we don't mix formatting styles, we didn't need this). They must have figured you still had too much opportunity to focus on your coding logic. You would rather use a part of your brain to figure out different constructor styles as well, would you not? Let's clutter the class declaration some more, just the class name, a base class and a number of interfaces is way too easy, let's throw in some arguments for no ffin' benefit at all. Way to go C# designers.
@nielshoogev1
@nielshoogev1 Жыл бұрын
Personally, I use records with required and init for objects that only contain data, and I use primary constructors for classes that do processing and participate in DI. I am very happy with these features and I am glad the C# designers added them.
@fayazvar3948
@fayazvar3948 Жыл бұрын
If i have some logic in Constructor.
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Don’t use primary constructors if that is the case. As you saw it is great when getting rid of assignments, but if you want a bunch of logic (which I avoid at all costs) then just standard constructors
@ak_nex
@ak_nex Жыл бұрын
This primary constructor sucks... 1. Most people prefer private field names with underscores. How stupid it would be to have smth like this: Person(string _name)... 2. And what about records? Their primary constructors behave differently. The parameters are not private fields but properties with "get" and "init" modifiers. It would make more sense to have the same implementation in both cases then
@JamesMontemagno
@JamesMontemagno Жыл бұрын
Don’t have to use them if you don’t like them… just like any feature. For me, I can see me using them in a high majority of classes I have today.
@ak_nex
@ak_nex Жыл бұрын
​@@JamesMontemagno in case when you need to change a class to a record, e.g. to copy properties using 'with', you might forget about the incompatibility of primary constructors and expose private fields as public properties. I'm sure each of us had the case at least once. So, this is my biggest concern
@diligencehumility6971
@diligencehumility6971 Жыл бұрын
C# were perfect around C# 8 or 7. Now it's completely bloated. This is exactly how it became bloated. "We want to make programmers write less lines" so now you have weird symbols and strange syntax everywhere that's nobody understands, it's less readable, it's not helping anything really, yeah it took 1 sec less to write my class hurray, now it's difficult to understand what's going on. Please stop it.
@ivankovachev8835
@ivankovachev8835 Жыл бұрын
I absolutely agree, I'd say C# 9 and .NET Core 3.1/5 was just right for me. Now they have too much stuff, they break too much old stuff, and you have to relearn stuff, because now the syntax is different or they work differently.
@JamesMontemagno
@JamesMontemagno Жыл бұрын
I think for me it is about using the features when and where they make sense for you in your apps. Most of my constructors are just dependency injected in so this cleans them up for me for sure. Also don’t sure new features if they aren’t your cup of tea, no one is forcing you too. They are also all built and proposed in the open :) go give some feedback!
@gregdennis6094
@gregdennis6094 Жыл бұрын
I know it's demo code, but.... WHY DOES YOUR PERSON HAVE A PRINTNAME() METHOD?! And then.... WHY ARE YOU INJECTING A LOGGER INTO IT?! These dependencies are so wrong!
@truebzyq
@truebzyq Жыл бұрын
Coding is not about "saving lines of code" but about readability, so all sexy blink blink code shortcuts are simply making language less readable, and less bugproff, and imagine that right now you are start learning programming in 2023 and someone just give you that class, with primaru constructor but you need to learn at first what constructor is, and the question is why? Why you have used 'l' in seconda constructor? Any problems with the same property name? Offcourse and then try to described it to a person that that just start learning programming. Its simply a nightmare.
@cethien
@cethien Жыл бұрын
it is pretty readable and "saving lines of code" also makes your code less prone to bugs
@obinnaokafor6252
@obinnaokafor6252 Жыл бұрын
So, every other languages that have primary constructor are less readable? Features such as this make C# more readable and succinct and less prone to errors.
@user-er7vl6rd3l
@user-er7vl6rd3l Жыл бұрын
Explain to your beginner why in all classes constructor parameters are tediously assigned to class fields, readonly:) Boilerplates occupied part of the class. Why?
@nielshoogev1
@nielshoogev1 Жыл бұрын
@@user-er7vl6rd3l In organizations where much emphasis is placed on the number of lines of code one produces, using a language that requires a lot of boilerplate is a bonus. IDE's can generate such boilerplate, code analyzers can check that there are no errors, so in the end the developer can claim having done a lot of work, almost risk free.
@user-er7vl6rd3l
@user-er7vl6rd3l Жыл бұрын
@@nielshoogev1 Probably all the objections of the discussion are based on this.
@Forshen
@Forshen 7 ай бұрын
I find this kind of code disgusting. There is too much happening under the hood and you have to have more knowledge about the feature / flow of the code. Your default constructor gives us a scope and a 'main line' about the executing of the code and how it all connects together.
@bobweiram6321
@bobweiram6321 5 ай бұрын
It's beyond disgusting! A primary constructor parameter can have the same identifier as a class member. Is it worth introducing a blatant language inconsistency for the sake of saving a few lines of code? It's a bad tradeoff.
@Forshen
@Forshen 5 ай бұрын
@@bobweiram6321 totally agree, less code != clean code
@iimv
@iimv 2 ай бұрын
this is the definition of bs. Nothing new, just different.
@RusWatcher
@RusWatcher Жыл бұрын
it only makes the code harder to understand. everything is scattered around the class.
C# Null Checks and Argument Validation - The Wise Approach
14:00
James Montemagno
Рет қаралды 9 М.
¡Puaj! No comas piruleta sucia, usa un gadget 😱 #herramienta
00:30
JOON Spanish
Рет қаралды 22 МЛН
WHY DOES SHE HAVE A REWARD? #youtubecreatorawards
00:41
Levsob
Рет қаралды 34 МЛН
Why I won’t need constructors anymore in C# 11
9:39
Nick Chapsas
Рет қаралды 134 М.
LINQ + Lambda expressions - C# tutorial
6:14
Tarodev
Рет қаралды 99 М.
8 await async mistakes that you SHOULD avoid in .NET
21:13
Nick Chapsas
Рет қаралды 307 М.
Configure YARP as a Reverse Proxy with .NET
24:54
James Montemagno
Рет қаралды 7 М.
WHY and HOW to Add .NET Aspire to ANY .NET API and Web App in Minutes
22:02
"Stop Using Properties in C#, Just Use Fields" | Code Cop #013
11:53
Inheritance | C# | Tutorial 31
10:29
Giraffe Academy
Рет қаралды 56 М.
ПРОБЛЕМА МЕХАНИЧЕСКИХ КЛАВИАТУР!🤬
0:59
Корнеич
Рет қаралды 3,4 МЛН
5 НЕЛЕГАЛЬНЫХ гаджетов, за которые вас посадят
0:59
Кибер Андерсон
Рет қаралды 611 М.
Карточка Зарядка 📱 ( @ArshSoni )
0:23
EpicShortsRussia
Рет қаралды 263 М.