The Ultimate Guide to C# Records

แชร์
ฝัง
  • เผยแพร่เมื่อ 2 ต.ค. 2024

ความคิดเห็น • 92

  • @curtmantle7486
    @curtmantle7486 8 หลายเดือนก่อน +40

    Devs should watch this even if they think they understand records.

  • @yufgyug3735
    @yufgyug3735 8 หลายเดือนก่อน +38

    'make invalid state unrepresentable' - that is an excellent line

    • @WillEhrendreich
      @WillEhrendreich 8 หลายเดือนก่อน

      Very idiomatic in fsharp, it's just a very natural way to get things done on that side of dotnet. It's an absolute joy to work with that philosophy.

    • @user-tk2jy8xr8b
      @user-tk2jy8xr8b 4 หลายเดือนก่อน

      Unfortunately you still can't have a truly non-nullable reference types nor guarantee struct initialization thanks to every type having `default`

  • @lorenzodepasquale
    @lorenzodepasquale 8 หลายเดือนก่อน +23

    That NonEmptyString is so elegant

  • @abj136
    @abj136 8 หลายเดือนก่อน +8

    To be sure, I 100% understood what you were describing about records in the opening of this video. But I knew approximately 0% of the syntax you showed after, so it’s a good thing I did not skip the rest of this video per your advice.

  • @Lonchanick
    @Lonchanick 7 หลายเดือนก่อน +5

    Enough material for at least 10 videos :) Nice!

  • @TheSeniorDeveloper
    @TheSeniorDeveloper 2 หลายเดือนก่อน +1

    It was very good explanations. Thank you

  • @williamturns1647
    @williamturns1647 8 หลายเดือนก่อน +4

    This was a succinct deep-dive into records. Could you kindly make one on pattern matching, too? There are countless ways to use them and it doesn't come naturally to think in pattern-matching style after years of using verbose conditions.

  • @kinglygaurav
    @kinglygaurav 8 หลายเดือนก่อน +2

    Besides learning records, if anyone wants to learn effective communication, watch this!

  • @DimitrisConstantinou
    @DimitrisConstantinou 8 หลายเดือนก่อน +4

    I wish i had your deep knowledge of c#

  • @nickbarton3191
    @nickbarton3191 8 หลายเดือนก่อน +4

    Didn't even think about deriving records, didn't know about equality.
    Glad to dump structs.
    Always learn something from these videos.

  • @matheosmattsson2811
    @matheosmattsson2811 8 หลายเดือนก่อน +5

    Love it. Used records a few times but always confused me what they really are tbh. Other than a quick way to create a small class (which is what I saw it as earlier). Now I'm kind of considering migrating a lot of classes to records.. Great video!

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +2

      You have made a valid point. In a domain model of a significant complexity, many types are actually values in their heart. Once you start recognizing those models, you will find many examples where records fit naturally.

  • @Mefator
    @Mefator 8 หลายเดือนก่อน +6

    You can also simply use *readonly record struct* to make its properties immutable by default.

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +9

      You are right, I should have shown that, too.

  • @ДмитрийКондратенко-б5ь
    @ДмитрийКондратенко-б5ь 8 หลายเดือนก่อน +3

    I wondering if records can be used as entity models working with EF

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      Not by default, because records are immutable by default and EF tracks entities by reference. Even the terminology uncovers the issue - EF is dealing with entities and records define values.

  • @HuneSilver
    @HuneSilver 8 หลายเดือนก่อน +3

    thanks for the subtitles in english are very useful 🙂

  • @mr_venik
    @mr_venik 8 หลายเดือนก่อน +6

    NonEmptyString record struct is nice, but in C# you can still use "default" keyword which would ignore parameterless constructor

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +3

      That is an interesting point about default. Did you check it? I can't find in the documentation whether it invokes the constructor or not.

    • @protox4
      @protox4 8 หลายเดือนก่อน +3

      @@zoran-horvat It does not invoke the parameterless constructor. It simply zeroes the struct. It would be hugely breaking otherwise (default is used to clear values to be GC'd everywhere).

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +5

      @@protox4 Yes, you're right. Thank you for this note, I will make sure to remember it the next time I speak about the same matter.

    • @user-tk2jy8xr8b
      @user-tk2jy8xr8b 4 หลายเดือนก่อน

      @@protox4 right, it's a straight memzero call. Likely that's the way lang designers answered the question "how do we initialize an array of a non-zero length"

  • @adollphus
    @adollphus 3 หลายเดือนก่อน +1

    Great content, thanks Zoran.

  • @TayyabMughalDIK
    @TayyabMughalDIK 8 หลายเดือนก่อน +6

    This is the best demo on records. It couldn't get better than this one.

  • @guilhermealves577
    @guilhermealves577 3 หลายเดือนก่อน +2

    One of the bests vídeos i watched in TH-cam. Pure gold.

  • @ДмитрийКондратенко-б5ь
    @ДмитрийКондратенко-б5ь 8 หลายเดือนก่อน +1

    Great video!

  • @ghevisartor6242
    @ghevisartor6242 8 หลายเดือนก่อน +1

    i'm dumb, since i'm using Blazor with JsInterop i had some objects that had to be passed between Blazor and javascript, I used a plain class with the IEquatable, when i could have just used record, i even knew about them. Ahh thanks for the video.

  • @gard2054
    @gard2054 2 หลายเดือนก่อน +1

    The best 13 min ever. Amazing explanation

  • @weluvmusicz
    @weluvmusicz 8 หลายเดือนก่อน +1

    In the record you can define required immutable properties like so: public required string FirstName { get; init; }

  • @kennyhendricks4293
    @kennyhendricks4293 7 หลายเดือนก่อน +1

    Damn!!! I love this, I generally use it in DTOs scenario

  •  8 หลายเดือนก่อน +1

    Good stuff. I was looking for the video to discuss with dotnet team in the format: let's meet after a week and discuss it. Your topics so far were in the shelve labeled "this could be too difficult for junios and mids", but this one is flexible. Juniors and seniors will find topics to discuss. Thank you.

  • @averyrealtree545
    @averyrealtree545 7 หลายเดือนก่อน +1

    What a wonderful guide! I love your concise and clear communication

  • @zo1dberg
    @zo1dberg 4 หลายเดือนก่อน +1

    Great vid and love your accent and storytelling!

  • @ДинаЛинская
    @ДинаЛинская 5 หลายเดือนก่อน +1

    Excellent, full and deep explanation, thanks a lot 🎉

  • @barionlp
    @barionlp 8 หลายเดือนก่อน +1

    never heard that i should use record structs over normal structs
    do you have any sources going deeper into that?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      C# reference is a good starting point: learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/record
      You can see from there what exists and then search further for details.

  • @mahmmoudkinawy2783
    @mahmmoudkinawy2783 5 หลายเดือนก่อน +1

    thank you! excellent explanations

  • @slowjocrow6451
    @slowjocrow6451 8 หลายเดือนก่อน

    It seems most objects I deal with have an Id. Is a record still suitable? It doesn't matter the equality of the other properties, only Id. And what about objects with many properties? Is a record slower?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      A record is just a class. Therefore, it applies in all situations where you would use a class. It is fine to add the ID to a record. You can even watch my next video where I have used a readonly record struct to define a strongly typed ID itself.

  • @lluism200
    @lluism200 หลายเดือนก่อน

    I really like the looks of records but how do you manage using them as value objects when inserting data to a database where an identity is required?

    • @zoran-horvat
      @zoran-horvat  หลายเดือนก่อน

      @@lluism200 If you think of ORM, then it is not meant to handle (immutable) records. Otherwise, it is straightforward. You can include an ID in the record if it corresponds to a database record.

  • @marcotroster8247
    @marcotroster8247 หลายเดือนก่อน

    Maybe I'm old school, but I don't like black magic. There's too much implicit behavior to reason about.
    It's a bit like reflection. Very powerful feature, but you'll never know how a change will impact the calling scope.

    • @zoran-horvat
      @zoran-horvat  หลายเดือนก่อน

      @@marcotroster8247 I don't think there is any room left for speculation. We already had all that with structs and nobody was ever confused.

    • @marcotroster8247
      @marcotroster8247 หลายเดือนก่อน

      @@zoran-horvat Maybe for enterprisy projects where you don't go into the hardware details it's fine.
      I've implemented quite some nasty bit hacks with C#, e. g. a card game. Each card is represented by a struct consisting of one byte, with several bitwise features encoded inside those 8 bits. Each player can have 8 cards. So the hand struct is an ulong of 8 bitwise concatenated cards. Then I apply all kinds of SIMD ops and compiler intrinsics to match card features in a hand with bitmasks. I also utilize class variables in the calling scope to avoid stack frame allocation (very fast). Plus I introduce unsafe fixed pointer access to the hand bytes to speed up array copying, etc.
      Now, would you feel safe to implement the card and hand as record structs when you don't know the exact memory representation? Even little / big endianess might matter. It's not so obvious now, isn't it?
      C# is quite versatile and your enterprisy way of coding might not perform well. Tbh, when I don't care about performance, I write my service in Python.

  • @chrisspire
    @chrisspire 7 หลายเดือนก่อน

    I would love to use records more but I have one doubt. Even if I just store values that are immutable, I often initialise SOME (but not all) values during creation and update OTHER later. Records don't seem to be in favour in that situation. Or maybe I can do RecordType x = x with {...} to create updated and in fact replace the old object? [I am rather a beginner;)]

    • @zoran-horvat
      @zoran-horvat  7 หลายเดือนก่อน

      You are right with your conclusion, but I must ask what is the reason for such practice? I am following the rule that every object must be complete and valid when created. Records are aligned well with that principle.

    • @chrisspire
      @chrisspire 7 หลายเดือนก่อน

      @@zoran-horvat I use API and there is an class (A) with all starting values when object is created. But these values change over life span of this object. I want to create a record that will store both the initial values of (A) and the values when the object is destoryed. Right now I have a class that copy starting values of (A) when (A) is created and copies values of (A) in the moment the object is destroyed. So half of my object values is filled when (A) is created and half when (A) is destroyed. At the end I serialize those values and perform futher statistical analysis on them.

  • @MC_DarkMaster
    @MC_DarkMaster 8 หลายเดือนก่อน

    Would that be an candidate for record struct? If it does make sense how would a record struct look like?
    public sealed class DateTimeRange
    {
    public DateTime Start { get; private set; }
    public DateTime End { get; private set; }
    public DateTimeRange(DateTime start, DateTime end)
    {
    EnsureStartIsBeforeEnd(Start, End);
    Start = start;
    End = end;
    }
    static void EnsureStartIsBeforeEnd(DateTime start, DateTime end)
    {
    if (start > end)
    {
    throw new DateTimeRangeException("The endtime must not be before the starttime");
    }
    }
    }

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      If you stored DateTime Start and TimeSpan Duration, with DateTime End being a calculated property, then you wouldn't need any validation.

    • @MC_DarkMaster
      @MC_DarkMaster 8 หลายเดือนก่อน

      @@zoran-horvat That is definetly an good option but would it be possible to to convert it to a record struct? And is an struct the right type for that? I find it very hard to decide when it is better to use an record struct instead of an record class

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      @@MC_DarkMaster The decision is the same as with any other type. A record struct is a value type, passed by value and copied on every assignment. A record class is a reference type, assigned and passed by reference. Therefore, you will use the form that you need. If you don't know what you need, then a class will be good enough until you find out.

  • @cloudycloudlet7091
    @cloudycloudlet7091 8 หลายเดือนก่อน

    Discord link is not working anymore :(

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      I don't know why "never expire, infinite users" Discord links keep expiring every time I share them... That hurts my programmer feelings.
      Try the new link now: discord.com/invite/AgPDChDpxg

  • @edkachalov
    @edkachalov 8 หลายเดือนก่อน

    C# invented record from Pascal

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      Nope. What you are referring to as Pascal record is struct in C#. It was borrowed from C, where it existed even before ANSI C and was borrowed from ALGOL where it existed quite some time before the coming of Pascal. The C# record, on the other hand, is something entirely different and it is borrowed from functional programming languages.
      I hope the matter is clearer now. It is not hard to figure.

  • @Sydra.
    @Sydra. 8 หลายเดือนก่อน +1

    Too awesome!

  • @cbgrasshopper
    @cbgrasshopper 8 หลายเดือนก่อน

    In a previous video, you recommended against using collections in records due to the issues with deep immutability. Based on this video, it seems you would not have the same concern if the record used frozen collections; is that accurate?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      Actually, my concern was with equality - collections don't overload Equals and GetHashCode, which are required by the record that might contain them. In that respect, immutable collections and frozen collections are immutable, but still not comparable for equality.

    • @cbgrasshopper
      @cbgrasshopper 8 หลายเดือนก่อน

      @zoran-horvat In that case, the only option would be a custom type wrapping a collection and implementing the necessary equality members?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      @@cbgrasshopper The question is what would be the purpose of that. I would rather opt for a common immutable class with no value typed semantics.

  • @HOSTRASOKYRA
    @HOSTRASOKYRA 8 หลายเดือนก่อน +1

    Thank you very much for your explanations!

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      Glad if it was useful.

    • @HOSTRASOKYRA
      @HOSTRASOKYRA 8 หลายเดือนก่อน

      @@zoran-horvat I hope so too, but the path of pure functional programming in C# still scares me.

  • @alexhall840
    @alexhall840 8 หลายเดือนก่อน

    Can you give some real world examples on using records. I am struggling to think of where I can use them in the business application I am working on.

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      Quite a few other videos on my channel are using records in domain modeling.

  • @nickw656
    @nickw656 8 หลายเดือนก่อน

    The later `record struct` makes the properties mutable by default. Does this seem like a backward trend?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      No, that's just how structs work. You can declare readonly record struct which is immutable by default.

  • @halorx9863
    @halorx9863 8 หลายเดือนก่อน

    Will you do F# somedays?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      I have no plans for that at this moment.

  • @1992jamo
    @1992jamo 8 หลายเดือนก่อน

    Your syntax is so absolutely alien to me always, but I find your videos very valuable.
    Things like var (firstName1, _) = samuelL; do not even look like C# to me. What is the variable here called?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      That is deconstruction of the record into a tuple, without actually creating a tuple. It stems from an old syntax where you can assign multiple variables in one statement, like (a, b) = (b, a). This will actually swap two values without the use of a third variable.

    • @1992jamo
      @1992jamo 8 หลายเดือนก่อน +1

      @@zoran-horvat That is extremely interesting, thanks for explaining. I don't think I'll use it, but I appreciate the lesson.

  • @ДмитрийКондратенко-б5ь
    @ДмитрийКондратенко-б5ь 8 หลายเดือนก่อน

    10:32, record struct could also be defined with readonly keyword.

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      Yes, I missed the opportunity to add that, too. That is a viable option when there is no validation.

  • @logank.70
    @logank.70 8 หลายเดือนก่อน

    Everyone should watch out when using the Primary Constructors feature. There is currently no way to mark the backing fields that it creates as readonly. Not a good feature to use in conjunction with Dependency Injection.

    • @David-id6jw
      @David-id6jw 8 หลายเดือนก่อน

      You can't make the class parameters readonly, but you can assign them to readonly fields of the same name, and any use in the class will prefer the field over the parameter, making access to the mutable parameter impossible.

    • @obinnaokafor6252
      @obinnaokafor6252 8 หลายเดือนก่อน

      the support is coming in C# 13

  • @alfonsdeda8912
    @alfonsdeda8912 8 หลายเดือนก่อน

    Hi Zoran, great video!
    Why class shouldn't derive from another class like in your example with name?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      Long story :)
      The short version is that the derived class then carries the unwanted baggage of its base, which may cause all kinds of issues later.
      Most frequently, it is better to have a clean abstract base which only provides services that are native to every derived type and nothing more.
      Saving a few lines of code gives little satisfaction when you encounter invalid or dubious assignments later in development.

    • @alfonsdeda8912
      @alfonsdeda8912 8 หลายเดือนก่อน +2

      @@zoran-horvatYes, I misunderstood early, I shouldn't inherit functionality that I don't need but rather work with composition.

  • @MC_DarkMaster
    @MC_DarkMaster 8 หลายเดือนก่อน

    Can you make a video when to use record structs and when to use record classes?

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน +1

      The decision is the same as in the case of class vs. struct.

    • @abj136
      @abj136 8 หลายเดือนก่อน

      But I thought the point of classes was pass by reference, which has the point of mutability. Once objects become immutible, the difference seems irrelevant.@@zoran-horvat

    • @zoran-horvat
      @zoran-horvat  8 หลายเดือนก่อน

      @@abj136 No it's not. Passing by value is an optimization for types that are small enough so that copying every time a value is used does not cost more than allocation, dereferencing, and freeing combined. For types that are as large as a pointer, the value type may take an order of magnitude less CPU cycles when used.

  • @zasugod
    @zasugod 8 หลายเดือนก่อน

    first