Тёмный
No video :(

Primary Constructors in C# 12 Explained! 

James Montemagno
Подписаться 138 тыс.
Просмотров 24 тыс.
50% 1

Опубликовано:

 

21 авг 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 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
@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
@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? 😂
@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?
@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.
@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.
@philippelhaus
@philippelhaus Год назад
Useful
@mtranchi
@mtranchi Год назад
like it!
@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()
@HOSTRASOKYRA
@HOSTRASOKYRA Год назад
When will they finally add a constructor method, without a class name?
@MohammadNikravan
@MohammadNikravan 9 месяцев назад
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 8 месяцев назад
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
@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 :)
@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
@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
@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.
@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.
@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.
@hj.0301
@hj.0301 Год назад
does it work with mapster's MapToConstructor?
@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.
@eriknyk2k
@eriknyk2k Год назад
I can see that it's borrowed from kotlin and I love it
@JamesMontemagno
@JamesMontemagno Год назад
🤣
@damiank6566
@damiank6566 8 месяцев назад
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.
@Forshen
@Forshen 9 месяцев назад
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 8 месяцев назад
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 8 месяцев назад
@@bobweiram6321 totally agree, less code != clean code
@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!
@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
@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.
@iimv
@iimv 5 месяцев назад
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.
Далее
ЛИЗА - СПАСАТЕЛЬ😍😍😍
00:25
Просмотров 2,5 млн
Primary Constructors in .NET 8
28:42
Просмотров 22 тыс.
Covariance and Contravariance
13:31
Просмотров 13 тыс.
why do header files even exist?
10:53
Просмотров 392 тыс.
Will All My Classes Look Like Records Now?
12:46
Просмотров 7 тыс.
What are record types in C# and how they ACTUALLY work
15:36
The Ultimate Guide to C# Records
12:55
Просмотров 18 тыс.
ЛИЗА - СПАСАТЕЛЬ😍😍😍
00:25
Просмотров 2,5 млн