Intro to Records in C# 9 - How To Use Records And When To Use Them

  Рет қаралды 138,647

IAmTimCorey

IAmTimCorey

Күн бұрын

C# 9 is out and with it comes a new, and somewhat confusing feature: records. In this video, we are going to look at what records are, how to use them effectively, and then we will talk about when they would be useful and, just as importantly, when you should not use them.
Source Code: leadmagnets.app/?Resource=Int...
Patreon): / iamtimcorey
Mailing List: signup.iamtimcorey.com/
Purchase courses: www.iamtimcorey.com
0:00 - Intro
0:57 - Getting started: demo console app
2:16 - How to use Records
3:45 - Records: declared and explained
6:55 - Record features
13:00 - Records vs. Class: ToString() override
17:04 - Records vs. Class: compare objects
20:49 - Records vs. Class: compare object reference
22:10 - Records vs. Class: compare object ==
24:31 - Records vs. Class: object Hash Code
27:10 - Records vs. Class: Recap
28:13 - Records vs. Class: Deconstructor
31:32 - Records vs. Class: Record Object copy
34:30 - About Records
36:19 - Record property access modifier
40:12 - Other Properties in Records
42:53 - Methods in Records
43:56 - Full Properties in Records
47:33 - Recap
49:49 - Record inheritance
52:57 - Why Records?
53:53 - /*Benefits*/
57:45 - /*When to use Records*/
1:05:10 - /*When not to use Records*/
1:14:31 - Summary and concluding remarks (+ bonus: top level call args in C# 9)
Thanks to Ralfs HBK for the chapters breakdown

Пікірлер: 421
@RalfsBalodis
@RalfsBalodis 3 жыл бұрын
0:00 - Intro 0:57 - Getting started: demo console app 2:16 - How to use Records 3:45 - Records: declared and explained 6:55 - Record features 13:00 - Records vs. Class: ToString() override 17:04 - Records vs. Class: compare objects 20:49 - Records vs. Class: compare object reference 22:10 - Records vs. Class: compare object == 24:31 - Records vs. Class: object Hash Code 27:10 - Records vs. Class: Recap 28:13 - Records vs. Class: Deconstructor 31:32 - Records vs. Class: Record Object copy 34:30 - About Records 36:19 - Record property access modifier 40:12 - Other Properties in Records 42:53 - Methods in Records 43:56 - Full Properties in Records 47:33 - Recap 49:49 - Record inheritance 52:57 - *Why Records?* 53:53 - /*Benefits*/ 57:45 - /*When to use Records*/ 1:05:10 - /*When not to use Records*/ 1:14:31 - Summary and concluding remarks (+ bonus: top level call args in C# 9) You forgot the time codes ;)
@chezchezchezchez
@chezchezchezchez 3 жыл бұрын
Yeah. U took a LOT of time to do it, when Tim already knew the times...
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks! MUCH appreciated
@chrisreddy3926
@chrisreddy3926 3 жыл бұрын
Thanks for such a detailed explanation, Tim. You are the best at explaining complex concepts and having the perfect analogies to better understand them. The house and address analogy for class addresses was brilliant.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You're very welcome!
@mandersson1979
@mandersson1979 3 жыл бұрын
Great educational presentation with high quality! And the chapter breakdown makes it easy to jump between the parts you find most useful.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad it was helpful! Give Ralfs thanks for the timestamps. He has done dozens of videos as a way to give back to this great community of viewers.
@samko6672
@samko6672 3 жыл бұрын
Thank you Tim, seriously this is the first time I know about Records in .Net core. Please give us all updates in C# as much as you can.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Records are brand new, so you haven't been missing anything. They were just released in November 2020.
@janekkelenkamp323
@janekkelenkamp323 3 жыл бұрын
Superman Tim Corey, could not resist getting into yer slipstream. Really great to have you on board. Thanks for yer forte which appears to be a mind boggling easy way to get into web development.
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 жыл бұрын
Thank you for the support!
@onyebuchiboss
@onyebuchiboss 3 жыл бұрын
Thanks Tim, I knew I could only get vivid description of the updates from you. Looking forward to the Blazor updates.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
More to come!
@Greatfulone
@Greatfulone 3 жыл бұрын
This is amazing; I was recalling concepts from Java Script and Java. It sounds like the smart people at Microsoft worked so hard to make available capabilities that make coding a lot easier. Things that in other languages you just have to remember how to do. But now in C# you have specific methods with specific results. I love it. And you explained it so well as always. Nothing against other languages I love them all, and wish I had time to learn more about them. But I am so glad I decided to learn C# and other Microsoft technologies.
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 жыл бұрын
Thanks for watching and sharing!
@kristianaranda
@kristianaranda 3 жыл бұрын
Great video, many thanks Tim! I'm definitely going to recommend your videos to my co-workers.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Please do!
@Stanley1551
@Stanley1551 3 жыл бұрын
Huge addition to C#, introduced with a great video! Thank you!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You're very welcome!
@F4C31355
@F4C31355 3 жыл бұрын
Thanks Tim, I wish you work for MS because your explanations are always crystal clear, unlike MSDN articles which sometime looks like "how to draw Owl" meme.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You are very welcome.
@chadox71
@chadox71 3 жыл бұрын
Thank you so much Tim, records definitely needed their own video.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Very welcome
@haroldpepete
@haroldpepete 3 жыл бұрын
Great, in my humble opinion, i think you deserve the c# crown
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thank you!
@JasonSobell
@JasonSobell 3 жыл бұрын
Awesome material, and a great explanation! For those trying it at home, there are a couple of syntax simplifications you can use: public record Record2(string FirstName, string LastName) { internal string _firstName = FirstName; internal string FirstName => _firstName.Substring(0, 1); public string FullName => $"{ FirstName } { LastName }"; }
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks for the tips!
@zulhishamtan4308
@zulhishamtan4308 3 жыл бұрын
Thank you very much for this valuable knowledge. Records - A value-added to C#
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You are welcome!
@CautFistic
@CautFistic 3 жыл бұрын
Thank you so much for the awesome video! Everything was very well explained! Only thing I was still wondering was if Records can inherit Interfaces or not. I searched the web and I see that they can! :)
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Yep, records are classes so they can implement interfaces or inherit from other records.
@expertreviews1112
@expertreviews1112 3 жыл бұрын
Absolutely top content Tim!! More power to you
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thank you!
@TheMindDunes
@TheMindDunes 3 жыл бұрын
Great video and Thanks for the detailed explanation Tim....
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You bet
@Danilo.Oliba.Suarez
@Danilo.Oliba.Suarez 3 жыл бұрын
Thank you Tim! This is a high quality Knowledge.!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
My pleasure!
@Laiteux
@Laiteux 3 жыл бұрын
Thanks a lot for this amazing video! You should definitely get used to the "Ctrl+D" shortcut tho :D
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad it helped!
@devmoth9274
@devmoth9274 3 жыл бұрын
Thanks for all the content you always deliver. I made huge progress in C# over the last year and your videos played a big part on that :) I have two examples where I'm still not sure what I would use: 1. A Coordinate. Usually it was a prime example for a struct. But with all the features of a record, i would tend to create it as a record now. The easy comparison, an easy destructor, immutability and also the ability to have for example a 3DCoordinate inherit from Coordinate. But this makes me wonder, what are cases to use a struct then? (I almost never used structs in the past, do i don't know that much about those) 2. Let's say we have a simple n:1 relationship between city and person (inhabitants) and none of the cities properties will ever change. Just the objects in the Collection for inhabitants. Would it make sense to use a record here, if i want to guarantee immutability?
@knudnielsen2258
@knudnielsen2258 3 жыл бұрын
Hi Tim, I'm going to Copenhagen academy in IT learning and I'm doing web programming in server, all my fellow students are more interested in your videos than in our teacher, I post all your free videos on our forum, well done Tim, I also buy your courses and learn a hell of a lot from them many greetings Knud Nielsen Denmark
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Awesome! I am glad they have been so helpful.
@knudnielsen2258
@knudnielsen2258 3 жыл бұрын
@@IAmTimCorey I have recommend you to person there start at university study at programming and they are thankfull for your videos, and I wish your lection in Blazor to christmas it's great's
@salarkazazi7584
@salarkazazi7584 3 жыл бұрын
Thank you so much Tim, no matter what level a developer is, ur uploads are great !
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad you like them!
@andrewthompson9714
@andrewthompson9714 3 жыл бұрын
Great video! Thoroughly enjoyable. I would just like to mention a couple of more use cases that records may be useful for. One thing I especially like about them, is how they can be declared with very little additional boiler plate code. They can be declared almost completely in domain language and they are compact, making them easy to read for non-tech oriented domain experts. They can be used as a tool for defining the domain knowledge in code, and being understandable between domain experts and developers! Another thing they can be really useful for is when combined with the new pattern matching features (Especially switch expressions) - They can be used as a reasonable substitute for discriminated unions, as they are able to be derived from - This, combined with pattern matching is a very powerful combination, and I think would probably warrant its own video. I loved the explanations, and I dont know why MS made the choice to allow mutability.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks for sharing
@branislavpetrovic7486
@branislavpetrovic7486 3 жыл бұрын
Great explanation of records in C# 9! Thanks Tim
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You are welcome.
@rossthemusicandguitarteacher
@rossthemusicandguitarteacher 3 жыл бұрын
Thanks Tim, this is a great video!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad you liked it!
@marcovonhagen
@marcovonhagen 3 жыл бұрын
☝🏾🔥👍🏽 That is a very good deep dive into records.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks!
@PauloMartins-ef3eu
@PauloMartins-ef3eu 27 күн бұрын
Excellente video indeed. Everything was thoroughly explained. Thank you!
@IAmTimCorey
@IAmTimCorey 26 күн бұрын
You are welcome.
@RalfsBalodis
@RalfsBalodis 3 жыл бұрын
You forgot your fav. Putting records in lists. It works. Thanks for the video :) Also 11:57 ctrl+d.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Yeah, I always forget the line duplication shortcut. I only use it in demos.
@bilalameen6171
@bilalameen6171 4 ай бұрын
Thank you very much TimCorey you explain very well. I guess we also can use records for const variables
@IAmTimCorey
@IAmTimCorey 4 ай бұрын
They won't provide you the same benefits as a const, but they are read-only (mostly).
@tooloudwind
@tooloudwind 2 жыл бұрын
Oh my god, this video contains huge amount of infomation. Thanks a million!
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
Glad it was helpful!
@sachinkainth9508
@sachinkainth9508 3 жыл бұрын
Sir, I love the way you teach.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks!
@OctavianUser
@OctavianUser 2 жыл бұрын
Very informative video. Other resources and even books don't cover that much about records!
@8982601240
@8982601240 3 жыл бұрын
बहुत ही अच्छा वीडियो टीम जी आप ऐसा ही ज्ञानपुर्वक वीडियो हमारे लिए लाते रहिए । हमारी दुआ आपके साथ है । धन्यवाद 🙏
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
बहुत-बहुत धन्यवाद
@empathetic24671
@empathetic24671 2 жыл бұрын
Thank you Tim for this awesome content. The comment section is educational as well.
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
You are welcome.
@dominicmartinez3085
@dominicmartinez3085 3 жыл бұрын
Thank you very much for this valuable knowledge.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
My pleasure
@ostelaymetaule
@ostelaymetaule 3 жыл бұрын
I will definitely reference this video to my colleagues
@StefanoLabate
@StefanoLabate 3 жыл бұрын
Wonderful explanation, very useful, thank you so much!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad it was helpful!
@StefanoLabate
@StefanoLabate 3 жыл бұрын
@@IAmTimCorey I've learned a lot from your videos, you really are a great teacher. Greetings from Italy!
@johnwolnisty7511
@johnwolnisty7511 3 жыл бұрын
Very informative. I did a couple of projects using Akka.Net. Since the objects passed around by Akka must be immutable, records are an excellent way to encapsulate the Akka message data and you don't have to worry about accidentally changing your object.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks for sharing
@mirragemelkyr
@mirragemelkyr 3 жыл бұрын
Woah as you said new shiny stuff, but "why"... I liked that you answered that question. Great Video
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad you liked it!
@richardc215
@richardc215 3 жыл бұрын
Great Tutorial. I enjoyed it and got a lot out of it.
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 жыл бұрын
Thanks for following Tim
@torrvic1156
@torrvic1156 6 ай бұрын
Thank you so much for sharing your vast knowledge with us, Mr. Corey! I think I am going to use this records for my DTO objects. This should work fine I guess because I don’t think they (DTOs) should be mutable.
@IAmTimCorey
@IAmTimCorey 6 ай бұрын
You are welcome.
@andrewthompson9714
@andrewthompson9714 3 жыл бұрын
Perfect timing, as I head for my lunchtime coffee !
@saurabhchauhan232
@saurabhchauhan232 3 жыл бұрын
Worried about 1:19:44 long coffee break 😀😂 just joking
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Yes, it does sound like a LOT of coffee.
@sfjadi
@sfjadi 3 жыл бұрын
Thank you for this awesome C# Record.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You are welcome.
@TonoNamnum
@TonoNamnum 3 жыл бұрын
At 10:38 of the video when you use the trick to initialize the field value from the constructor, it's even faster if you do Control + Dot on the private field instead of on the parameters of the constructor. In other words have an emty constructor then do Control+Dot on the field and select the option to "Initialize from Constructor". Long video but great thanks Tim
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Yep, that works too.
@jonchicoine
@jonchicoine 3 жыл бұрын
Hey Tim, Good stuff, thankyou. Call me crazy but I could swear you said multiple times "location on disk" when differentiating between a record and class You said it so many with confidence it makes me think i'm missing something. (one of us is going crazy :))
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
I'm not sure if I said disk but I did talk about the physical location of the class instance. That would be the location in memory that is carved out to store your class instance. With a record, when you copy it using the with statement, you are duplicating all of the values into new memory storage. With a class, when you change a value, you are just changing that specific memory value to be something different.
@jonchicoine
@jonchicoine 3 жыл бұрын
@@IAmTimCorey Yes, i know.... but you said "location on disk like 5 times". No worries. Will be interesting to see how this new Record thingy is used.
@jonchicoine
@jonchicoine 3 жыл бұрын
@@IAmTimCorey Well... perhaps not 5 times, but for sure 2 or 3 at least. You can hear an example of this at 24:11.
@jeffmair
@jeffmair 3 жыл бұрын
I was also wondering about this. Glad Tim replied to clarify it wasn't intentional.
@KouroushMetal
@KouroushMetal 3 жыл бұрын
Nicely done. Thank You!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks for watching!
@paulofernandoee
@paulofernandoee 2 жыл бұрын
excellent work in this video, thanks
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
You are welcome.
@seventhsunsoftware800
@seventhsunsoftware800 3 жыл бұрын
Really great explanation!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks!
@stevenkurtscholz
@stevenkurtscholz 3 жыл бұрын
Hey Tim, love this video. Totally unrelated but I wanted to let you know that if you do ctrl + enter at the end of a line, it will copy it and put in the next line. I saw you doing a manual copy paste :) Nice shortcut when you want to copy and paste a line. Thanks again for the vid.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Great tip!
@1eyewonder27
@1eyewonder27 3 жыл бұрын
Thanks for another great video Tim! At 10:58, what I have also learned from the 'Ctrl + .' boiler plate reduction is you can type your 'firstName' and 'lastName' parameters before typing them as properties. When you 'Ctrl + .' it will give you the option to create the parameters as properties or fields. I have found this helpful in creating DTOs and dependency injection.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Great tip!
@mastercompuk
@mastercompuk 3 жыл бұрын
Hi Tim great video as always. I'm watching all yours video and very often you are copying line of the code using copy and paste. I have found very useful to put the cursor on the line that I want to copy and press CTRL+D to copy whole line and paste below. Thank you for sharing your knowledge.
@OrionTRC
@OrionTRC 3 жыл бұрын
What Luke S just said also works if you select a whole block (say, a method you want copied to make an async version). Oh, and that Ctrl+dot thing on the constructor, to initialize your properties? Try selecting one (or more) properties and hitting Ctrl+dot. It'll ask if you want to initialize it in a constructor... it'll even create the constructor for you if you don't have one yet! :D Saves much typing.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Yep, I just forget that shortcut since I use it so infrequently (mostly just for demos).
@AegirAexx
@AegirAexx Жыл бұрын
Great video. Thanks a lot!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@elioscipioni
@elioscipioni 9 ай бұрын
Great video!!
@IAmTimCorey
@IAmTimCorey 9 ай бұрын
Thanks!
@nanny07
@nanny07 3 жыл бұрын
Great video Tim! Very clear like all your others one. Just one small observation! public record User1(int Id, string FirstName, string LastName) : Record1(FirstName, LastName); I think that this line is a bit of confusing because it's the same thing of write: public record User1(int Id, string FirstName, string LastName); The example that would have made the most sense would have been to inherit from Record2 in order to show more clearly that the methods/properties/etc will be inherited too
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Your line isn't the same as mine - Record1 has a constructor and we need to pass data into that constructor to satisfy it. So, when we inherit from Record1, we also tell it which two properties to send into Record1's constructor.
@BelchamberUs
@BelchamberUs 3 жыл бұрын
Great as always, thank you Mr. Corey! So records are immutable unless you add setters and make them mutable, got it :-).
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 жыл бұрын
Thanks for watching!
@KakoriGames
@KakoriGames 3 жыл бұрын
Once I saw a Python talk (I also code in python) and in that talk one thing stuck with me: "Every feature [...] has at least one or two very clear and unambiguous mental models [...] for where is actually useful." The talk was about some python features, like metaclasses, but I found that this thought process can be applied for most of programming in general. I believe is more importante to understand a feature in a abstract level (its mental model/purpose) rather then all the technicalities that you can look up in the documentation. Same goes for records. What is a record, in real life? According to a dictionary: "1. a thing constituting a piece of evidence about the past, especially an account kept in writing or some other permanent form." It stores information about the past. We can't change the past, so we shouldn't change records. So there you go, records are for things that we cannot, or should not, change over time. Those mental models really help me get a hold of when to use certain features.
@carlinhos10002
@carlinhos10002 3 жыл бұрын
That's why I believe set shouldn't be valid for records, only init. But I think they've focused too much on the value equality and other stuff and forgot about this
@chezchezchezchez
@chezchezchezchez 3 жыл бұрын
You don’t update the number of victims when the serial killer strikes again? I think we need to update his record. 😎
@carlinhos10002
@carlinhos10002 3 жыл бұрын
There'll be a new record of a new crime. No past records would change
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Nicely done, thanks for sharing
@MrNickygr
@MrNickygr 3 жыл бұрын
Very nice explanation, thanks
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
You are welcome
@hubertprzybylski6610
@hubertprzybylski6610 3 жыл бұрын
Thanks you for that tutorial. Is it amazing !! :)
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 3 жыл бұрын
Thank you for continuing your learning with Tim.
@marcoantoniomuzulflores6391
@marcoantoniomuzulflores6391 Жыл бұрын
10:30 There's actually an even faster way to do it, you select all the properties that you want in your constructor, then hit alt + enter, there's an option that says generate constructor, it will generate all the constructor for you. You don't have to write anything. I use visual studio 2022 but idk if you can use it in 2019 and below.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thanks for sharing!
@sokreth
@sokreth Жыл бұрын
Hi, I was looking for a spread operator in C#, I think record just fit with the Blazor-state. Great tutorials, thanks.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@adamm9706
@adamm9706 2 жыл бұрын
More people need to watch this video!! I was having a hard time understanding records and this cleared everything up!
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
Excellent!
@HenrikRClausen
@HenrikRClausen 3 жыл бұрын
I'm using records with Dapper now, and it's working out just fine. Then, I have a different approach to data that needs to be changed/updated: I use the copy feature of records. That makes it distinctly clear exactly which fields will be changed. That's a lot more readable than using classes and having to copy every property. Using a record copy exposes clearly what my intentions are, and leaves much less space for bugs to hide in. All my records are still immutable, my code is brief and focused on what I do. it's good :)
@TedFanat
@TedFanat 3 жыл бұрын
Great stuff!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks!
@pilotboba
@pilotboba 3 жыл бұрын
Wow, I missed the ability to omit a type during instantiation in c# 9. That's nice, my eyes crossed when you first used it.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Good stuff!
@ranjanmaithani6263
@ranjanmaithani6263 3 жыл бұрын
Timestamp please?
@gonzalopinodavila112
@gonzalopinodavila112 3 жыл бұрын
Thanks Tim, that’s a good video. I have a couple of questions: records support generic, and the other one is if do you think that is a good idea that a record has a class as property. I’m designing a generic results from transactions that returns if the transaction was succeeded, has errors and if it is success, return the object persisted in the db
@panirajn
@panirajn 3 жыл бұрын
I really thank you for this video tutorial
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Glad it was helpful!
@mutalibgozalov7208
@mutalibgozalov7208 Жыл бұрын
awesome, thanks again
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@webbi1540
@webbi1540 3 жыл бұрын
Thanks coach!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Any time!
@pawebielecki887
@pawebielecki887 3 жыл бұрын
After watching I was dying to check this out: static void Main() { var r1 = new Record1(); var r2 = new Record1(); Debug.Print($"r1: {r1}"); Debug.Print($"r2: {r2}"); Debug.Print($"r1 == r2: {r1 == r2}"); } public record Record1() { public int RandomNumber => new Random().Next(0, 100); } What do you think the last Debug.Print will produce? Take your guess! :D P.S. Thank you Tim for another great video!
@Coeur85
@Coeur85 3 жыл бұрын
thanks Tim for the time and effort , try using CTR+D to duplicate lines in vs
@chezchezchezchez
@chezchezchezchez 3 жыл бұрын
Cool! I didn’t know that. I have vsVim installed and I do yy p 🥸
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Good tip!
@mangeshdashmukhe1776
@mangeshdashmukhe1776 2 жыл бұрын
I certainly found the use case for records in our project. For serverside caching, we calculate the SHA256 hashcode of the requests to identify if the request getting repeated, I see records as a potential replacement for classes there as we don't need to change the incoming requests and want the same hashcode every time the same request comes. Scope to get rid of SHA256.
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
Nice!
@ABMedia83
@ABMedia83 3 жыл бұрын
@ IAmTimCorey I like using record's when working with Json (System.Text.Json). I write a record that describe my format, then I serialize and desterilize it when needed. Also, I like using the custom Deconstruct void in my record to do Pattern Matching.(Fun Stuff)
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Great!
@johnconnor9787
@johnconnor9787 3 ай бұрын
34:43 Difference between struct and record 36:02 Records can have methods and can inherit from other records 52:59 Why we need records
@Edzward
@Edzward Жыл бұрын
"Personality, I wish that classes would do this". Same. For a lot of my classes I simply override ToString() to output a json representation of the class. For the className I simply declare it as a string.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Maybe someday.
@Maxim.Bordyug
@Maxim.Bordyug Жыл бұрын
Thank you for the big fonts.
@IAmTimCorey
@IAmTimCorey Жыл бұрын
You are welcome.
@amirdar
@amirdar 2 жыл бұрын
Great video as always! just got around to learning this. 1 quick question - where would you define those records? in classes, we usually define each class in its own file is this the same for records?
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
It depends. I like them to have their own file, but sometimes it doesn't make sense.
@LiteOS
@LiteOS 2 жыл бұрын
Hey @Tim about inheritance can class inherit from record to save writing code ? ty
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
A class cannot inherit from a record.
@logank.70
@logank.70 3 жыл бұрын
I would add that records are useful when writing more functional code (c# seems to be migrating to be a hybrid language) and if you are using records it should be records and immutability all the way down. A developer can run into issues if a record has a class that is mutable making the record shallow immutable. They do a solid 85% of the work for us but you can still shot yourself in the foot.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
It is possible. Thanks for sharing.
@chrisleebear2600
@chrisleebear2600 Жыл бұрын
Thanks!
@IAmTimCorey
@IAmTimCorey Жыл бұрын
Thank you!
@OldCumbria
@OldCumbria 3 жыл бұрын
Many thanks for this video. I have a couple of queries: 1. Can we place records in a list? 2. Can we use them in as Models in MVVM (E.G. PersonModel)?
@phizc
@phizc 3 жыл бұрын
Yes, and yes.
@OldCumbria
@OldCumbria 3 жыл бұрын
@@phizc Thank you.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Vemund is correct, although typically in MVVM you want to make changes to your model. In that case, you would want to use a class.
@OldCumbria
@OldCumbria 3 жыл бұрын
@@IAmTimCorey Many thanks. That confirms what I thought.
@ilanl74
@ilanl74 2 жыл бұрын
I think records are good candidate for dictionary keys
@devenshah1460
@devenshah1460 3 жыл бұрын
Tim, thanks for this in-depth video. I have one question, can we override Equals like we can in classes? Use case for this can be when I want to compare only selective fields for equality.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Yep, you can.
@TheMista90
@TheMista90 3 жыл бұрын
Excelente video, the only observation I see is that if records are basically classes with add in functionality, how they interact with interfaces?
@phizc
@phizc 3 жыл бұрын
You can use interfaces as normal. Just make sure any init properties are get only in the interface.
@vitaliykoritko5080
@vitaliykoritko5080 3 жыл бұрын
Thank you, suggest to add how to apply attributes to properties : public record Record1( [property: JsonPropertyName("id")] string Id)
@arashnsi421
@arashnsi421 2 жыл бұрын
thank you 👍👌🏻
@IAmTimCorey
@IAmTimCorey 2 жыл бұрын
You are welcome.
@gojakd
@gojakd 3 жыл бұрын
Wow, its a real deep dive in to record.. I wondering what is a way to use a record in foreach or for loop?
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Sure, it works just like any class.
@DeathxStrike18
@DeathxStrike18 2 жыл бұрын
I know this is old but once you override the properties you have to make a constructor and deconstructor for the overridden value for it to retain its original functionality, the reason is you changed it to a non-positional record, similar to how a list works. You told the record I need this to behave differently so it pulled the value from its position does the changes you declare then pops it back at the end as it moves in order. So in your example Last name moves to the front of the order and the changed Firstname moves to a new position behind it. The reason you can use { Get; Set; } is because you need to be able to use them for a public record struct as a struct cant be {get; init; } your case in Do not do is an exploitation of this behavior by hybridizing a loophole. When making the record a struct it takes on the behavior of a value type not a reference type removing the need of immutable. In fact as an example: public record struct Point(float x, float y) //initializes as public struct Point { public float X { get; set; } public float Y { get; set; } public Point(float x, float y) { X = x; Y = y; } } unlike public record Point(float x, float y) //initializes as public class Point { public float X { get; init; } public float Y { get; init; } public Point(float x, float y) { X = x; Y = y; } }
@Radhakrishna-pq3yj
@Radhakrishna-pq3yj 3 жыл бұрын
Tim Sharp Corey 👍👌
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks
@OctavianUser
@OctavianUser 2 жыл бұрын
I'm not sure about 1 part regarding inheritance: For example there is base Employee record and its derived record Manager. If I write Person p = new Manager(...); As expected I dont have access to Manager members untill I do explicit cast, but. Why p.ToString() prints Manager and even its members in {}, instead of Person? I have only guesses. Is it overrides ToString at runtime or even implicitly converts whole p instance ?
@daa82
@daa82 2 жыл бұрын
Thanks Tim! Would be great if you could condense these to 20 min max. Trying to watch this using 2x but it still feels slow.
@tomthelestaff-iamtimcorey7597
@tomthelestaff-iamtimcorey7597 2 жыл бұрын
That is what his 10 minutes series is intended to address - kzfaq.info/get/bejne/r6-IpNFisZ3Uj2g.html
@T___Brown
@T___Brown 3 жыл бұрын
@8:00 you are comparing init properties to the record and that your previous video etc. and that you can set those values via curly braces during construction. Is there a way to do that with Records? When I am trying it, I am required to use the constructor. Is there some option I missed in your video to allow me to use curly braces construction?
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
If you have a constructor, you need to use that unless you also create an empty constructor (just like with a class).
@humanisatitle
@humanisatitle 3 жыл бұрын
Great! 😊
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Thanks!
@bphatness3924
@bphatness3924 3 жыл бұрын
the equality checks make records compelling for me. I worked on a project where we kept multiple versions of documents in mongo, so on ingress (creation) we would find an existing, and compare so as to create a new version. Needless to say, we had to override gethashcode based on each of the properties, and then write/maintain equality tests for each such class.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
That sounds like a good option.
@tharindu79
@tharindu79 3 жыл бұрын
Hello Tim, I listened to the whole thing. Very informative, but one last bit you said around 1:13:15 tripped me. You said the record clone is making a shallow copy. But how so? We didn't have any reference types as any properties in the record to begin with. What exactly is shallow copied when you clone a record? Did you mean the reference to the record itself is reused on a clone?
@mwasplund
@mwasplund 3 жыл бұрын
In C# strings are reference types, so in this case when he is creating a new record from a copy of the original and replacing the FirstName value the new instance re-uses the LastName string. This works nicely with multiple levels of records since each instance is immutable so keeping references all over the place as you change only parts of a sub-record is a great performance gain without worrying about state changing underneath you.
@thorton70
@thorton70 3 жыл бұрын
Great info Tim! Much appreciated. I crack up every in you mention 'is/is not' since those have been in VB4 (pre-DotNet) as well as var (aka..Dim) In a class I usually override ToString(), add properties to a StringBuilder to return property names and contents. Records eleminate that extra code. Cool!
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
That's where I learned to love it. I missed it and now we finally have it.
@kirillzlobin7135
@kirillzlobin7135 3 ай бұрын
5:58 - Records act like value types, but they are not 7:44 - Meaning of "init" keyword 8:03 - Records are immutable 17:22 - Records equality 21:04 - Reference equality 23:27 - Equals() and == are not the same 28:19 - Record deconstructor 32:00 - Copying and modifying records
@_grzehotnik
@_grzehotnik 3 жыл бұрын
Is it possible to cast record to class? Let's say they have the same properties. First what comes to my mind is using reflection to map the properties. What if i wanted to use json.net to map a json to a record? Does the reflection with classes and records work the same way? (I assume it does since you said record is just a fancy class)
@nielsterheijden1486
@nielsterheijden1486 3 жыл бұрын
How do records differ from readonly struct? And how does changing the properties of a record like first letter for firstname the equality between records? Is Tim Corey the same as Timothey Corey? Can you also make them case insensitive? Or if one of your properties is a List does,t that break the immutability and the equality? When you do inheritance and you cast user1 to record1 and compare two different Id users with the same first and last name will they equal true?
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Records are reference types, structs are value types. Records can inherit from other records and can implement interfaces. Structs can do neither. Records are passed around via the reference (the address to the location where the house is) while structs are copied when they are passed around (building a new house each time). As for equality, records do a comparison of each field, so "T" is not "Tim" and neither is "Timothy". Also, case does matter so "tim" is not equal to "Tim".
@andywalter7426
@andywalter7426 3 жыл бұрын
I found a case where something should be a record even if there is one property you can write to. Here is a sample case. public record ConnectionInfo(string ConnectionID, string UserID, bool IsConnected) { public bool IsConnected { get; set; } } By still using records, I get the benefits of equality. Plus I get the benefit of having everything in the constructor and if i need to read the values, then i get that benefit as well. There can be many cases where most of the properties are immutable but there is one exception. In that case, I like a person can still use records to still have less boilerplate code.
@IAmTimCorey
@IAmTimCorey 3 жыл бұрын
Don't confuse a need for read-only properties with a need to be a record. A record should be an all or nothing solution. If you need some properties to be read-only, use the "init" keyword instead of set in your properties of a class and it will work the same way. You can also override ToString and the rest to get you where you need to be.
@keenkidash7616
@keenkidash7616 3 жыл бұрын
45:26 Actually, C# will handle way better that we will, TBH. I like the idea of having immutable data philosophy and being closer and closer to functional paradigms in this C# new era. In my opinion, record types comes with lots of extra stuff which is only shadowing what they should be, which is *immutable data structures* . The idea of redeclaring properties and the ability to declare methods makes records less responsable. *Data structures must store data* , nothing more, nothing else. If any system needs to hide some properties from a certain data structure or maybe remapping some of their properties, then the system must do it by itself (by implementing filters, mappers, handlers, etc), not the actual data structure.
@wealthgenerationstrategies
@wealthgenerationstrategies 7 ай бұрын
Interesting catch on the use of the internal keyword. Though it should be seen by the declaring class, it's not. Unless M$ considers the declaring class to be the record itself, as it is declared there. But you can sell see it externally, Hmmmmmm. Weird.
@levkurbanov431
@levkurbanov431 3 жыл бұрын
Hello, Tim. Thank you for this lesson. It was very interesting and useful. But I have a question. As I know all types for collections are reference types. And I can't use List or Array type for property in record because their hash codes will be different for different objects. So how can I work with record type that has to contain collection?
@guiorgy
@guiorgy 2 жыл бұрын
Did you get an answer?
@levkurbanov431
@levkurbanov431 2 жыл бұрын
@@guiorgy, Nope. I use records just for value and primitive types. In other cases I use classes to avoid misunderstanding of object immutability.
@levkurbanov431
@levkurbanov431 2 жыл бұрын
@@guiorgy, or you can write your own collection type and override GetHashCode and Equals methods. Also there are some types that implement IReadonlyCollection, but I didn't investigate how they work. May be these types can garantee that hash codes will be the same for same collections. Need to check it.
@guiorgy
@guiorgy 2 жыл бұрын
@@levkurbanov431 From a quick Google, seems that readonly collection also don't work. You'd have to extend collections with value semantic Equals and hashes, and if not careful, something else might break, like Json deserialization. In general, reference types without value type semantics should be avoided in Records, I guess. Source: stackoverflow /a/69840868
Андрей Дятлов. Что нового в C# 9
40:46
CodeFest Russia
Рет қаралды 891
Nastya and SeanDoesMagic
00:16
Nastya
Рет қаралды 44 МЛН
Я не голоден
01:00
К-Media
Рет қаралды 8 МЛН
Получилось у Миланы?😂
00:13
ХАБИБ
Рет қаралды 6 МЛН
What's New in C# 8.0 - Is There Multi-Inheritance Now?
1:23:33
IAmTimCorey
Рет қаралды 62 М.
Intro to MediatR - Implementing CQRS and Mediator Patterns
1:21:50
IAmTimCorey
Рет қаралды 221 М.
Stop, Intel’s Already Dead!
13:47
Linus Tech Tips
Рет қаралды 787 М.
5 New Features in C# 9 (not including Records)
1:11:00
IAmTimCorey
Рет қаралды 80 М.
10 C# Libraries To Save You Time And Energy
33:59
IAmTimCorey
Рет қаралды 205 М.
Why is C# Evolving This Way?
15:02
Zoran Horvat
Рет қаралды 21 М.
What's New in C# 12 | .NET Conf 2023
35:28
dotnet
Рет қаралды 55 М.
Nastya and SeanDoesMagic
00:16
Nastya
Рет қаралды 44 МЛН