How type deconstruction keeps your C# code clean

Sdílet
Vložit
  • čas přidán 15. 12. 2021
  • Check out my courses: dometrain.com
    Become a Patreon and get source code access: / nickchapsas
    Hello everybody I'm Nick and in this video I will talk a feature called deconstruction in C#. It is a feature I really see underutilized and I'd like to change that by showing you how awesome it is.
    Don't forget to comment, like and subscribe :)
    Social Media:
    Follow me on GitHub: bit.ly/ChapsasGitHub
    Follow me on Twitter: bit.ly/ChapsasTwitter
    Connect on LinkedIn: bit.ly/ChapsasLinkedIn
    Keep coding merch: keepcoding.shop
    #csharp #dotnet

Komentáře • 206

  • @AlFasGD
    @AlFasGD Před 2 lety +185

    If you've been watching Nick at all, you'd know he loves the numbers 69 and 420 for unknown reasons

    • @discipuloschristi6787
      @discipuloschristi6787 Před 2 lety +4

      69 dudes! m.czcams.com/video/zYWT4uYOPvs/video.html

    • @kippie86
      @kippie86 Před 2 lety +33

      What do you mean, he loves them? He always picks completely random numbers.

    • @Delphi80SVK
      @Delphi80SVK Před 2 lety +36

      @@kippie86 random from set (69,420) 👍

    • @scodadude
      @scodadude Před 2 lety +2

      Lol I just commented about the same exact thing.

    • @scodadude
      @scodadude Před 2 lety +3

      So casual. 😂

  • @AlFasGD
    @AlFasGD Před 2 lety +28

    Something to note; deconstructors were originally shipped with the var (x, y) syntax, it was only later when they added full support for the (var x, y) syntax, where you can have mixed assignments and declarations from a deconstruction, say if y was already declared you can now only declare x from the same deconstruction you assign the value to y.

  • @DisturbedNeo
    @DisturbedNeo Před 2 lety +14

    I didn’t know Key-Value pair had a deconstructor, that’s gonna be really useful when iterating over a Dictionary

  • @justinharris6197
    @justinharris6197 Před 2 lety +16

    I already use deconstruction a lot and didn't think I'd learn anything from this but then you did a deconstruct extension method and that I didn't know about.

  • @Dustyy01
    @Dustyy01 Před 2 lety +72

    Can u make a video about Finalizers vs Disposables?
    Most people getting into the topic dont understand the difference or the use case

    • @frotes
      @frotes Před 2 lety

      This!

    • @yp5387
      @yp5387 Před 2 lety

      Yes..

    • @Denis-nq1nc
      @Denis-nq1nc Před 2 lety +8

      Disposable clear everything right after exits using statement
      Finalizers will clear everything in some unspecified future when GC decides there's not enough memory,
      So in short use Disposable when it's critical to clear everything up right after using it like open files, database connection

    • @joaogabrielv.m328
      @joaogabrielv.m328 Před 2 lety

      Up!

    • @skyake59
      @skyake59 Před 2 lety +2

      Generally, finalizers should be avoided as much as possible for they have negative impact on GC.

  • @andrewrichesson8627
    @andrewrichesson8627 Před 2 lety +19

    Seems like it would be really easy to mess up variable ordering/mapping when calling the deconstructor. The deconstructor is also invisible and might confuse someone new to the code base. Deconstructors should probably be left to tuples and key value pairs.

  • @umilmi81
    @umilmi81 Před 2 lety +1

    If Nick Chapsas and Tim Corey had a baby that baby would make C# tutorial videos at exactly the right pace.

    • @nickchapsas
      @nickchapsas  Před 2 lety

      Speed Tim’s playback up or slow mine down. There is no perfect pace for everyone

  • @codewing
    @codewing Před 2 lety +3

    That's funny, I've used it yesterday because my IDE suggested it when switching from tuples to a struct and now I'll get it explained it a bit in more detail..
    Thanks a lot for the background info!

  • @arkord76
    @arkord76 Před 2 lety +7

    I indeed didn't knew the deconstruction feature. Thank you for explaining it!

  • @MrAndrei4777
    @MrAndrei4777 Před 2 lety +1

    Thank you Nick! This one turns out to be very handy. I will apply that tomorrow ASAP.

  • @mertkurt947
    @mertkurt947 Před 4 měsíci

    Wow, very informative for different scenarios. Thank much

  • @Denmaverick39
    @Denmaverick39 Před rokem

    Never know all this C# code until you deconstruct it hahaha. Thanks Nick!

  • @ferryutomo7051
    @ferryutomo7051 Před 2 lety

    I have been doing this in JavaScript, and finally it comes in C#. Thanks for sharing!

  • @veritasaequitas9875
    @veritasaequitas9875 Před 2 lety +2

    When you think about it a Deconstructor is the opposite of a signed Constructor.
    The Constructor injects data into the object for internal use.
    The Deconstructor ejects data from the object for external use.

  • @ardavaztterterian1211
    @ardavaztterterian1211 Před 2 lety +2

    I hope one day Nick will make a behind the scenes video involving the 420s and 69s he has been hinting for almost all his videos.

  • @TheRuko15
    @TheRuko15 Před rokem

    I've been wondering how to do this for so long. Thank you!

  • @PratikBhattacharya3010

    This is awesome! Thanks for sharing.

  • @chaunpt2404
    @chaunpt2404 Před 2 lety

    Thank you for an informative and inspiring video!

  • @robertmrobo8954
    @robertmrobo8954 Před 2 lety +1

    One of the new things I learned from this video... DateOnly
    Thanks Nick. ❤️❤️❤️

  • @ramigamal6637
    @ramigamal6637 Před 2 lety

    So simple, thank you.

  • @CrapE_DM
    @CrapE_DM Před 2 lety

    So glad to know how C# does this (and what they call it)

  • @JorgeLuisMachadoTorres

    bloody hell I didn't know we can extend to deconstruct :D good one dude

  • @twiksify
    @twiksify Před 2 lety +1

    Deconstruct can be overloaded as well, such that the consumer of your API can be as granular as they want without having to discard.

  • @xavier.xiques
    @xavier.xiques Před 2 lety

    Good video. Thanks!

  • @sujitwarrier4857
    @sujitwarrier4857 Před 2 lety +1

    Nice so destructuring from js is brought in.

  • @broodja5384
    @broodja5384 Před 2 lety

    "Just a number!"
    Nice!

  • @leonardozambonelli8946
    @leonardozambonelli8946 Před 2 lety +26

    Sincerly, i consider that deconstructor a new way to get code less readable. If i watch the code outside visual studio(so no intellisenze, no tooltip, etc..), it' quite weird understand variable types, and other stuff.

    • @veritasaequitas9875
      @veritasaequitas9875 Před 2 lety

      That's a good point. Readability is key in the development of clean code. If you look at my coding there will always
      be an initialisation section at the top of the program where you will find a reference to variables used in the program.
      Particularly reference types. It doesn't matter what teh language is. It's a basic principle. Of structured coding.
      I am wondering as I look at that line (var fullName, var dateOfBirth) = nick what the scope of those two variables are.
      Still, it's worth having a play around with this stuff don't you think? I will give it a go.

    • @Ownage4lif31
      @Ownage4lif31 Před 2 lety +1

      I agree. Seems like a feature to just add more confusion. I don't like it when code is less readable. Such features like this are handy for personal projects but not real projects where you work in teams. Imagine having to check the class just to see what the objects may be to save a couple of seconds lol.

    • @veritasaequitas9875
      @veritasaequitas9875 Před 2 lety

      It's not difficult to write extremely complex and contrived code. The reason I don't is because, as a freelancer, I am aware that some poor sap would have to figure it out some way down the line after I have delivered the project and moved on. Lean and clean.

  • @okbrown
    @okbrown Před 2 lety +1

    And again the JavaScript in me is happy!😂 Thanks Nick!

  • @stephajn
    @stephajn Před rokem +1

    I wish it worked more like it does in JavaScript where you could arbitrarily just name a property you want from an object and even give it an alias variable name and it works. Here in C# it feels much more limited and you have to know in advance the order in which to ask for your properties, or even know internals about the order in which a deconstructor method returns its parameters.

  • @scodadude
    @scodadude Před 2 lety +2

    I like how in the last few videos I've watched you've defaulted to using values like 420 and 69 without even thinking about it. 😄

    • @yatlor
      @yatlor Před 2 lety +2

      He was definitely thinking about it on an aysnc thread

  • @rumplin
    @rumplin Před 2 lety

    Hey Nick, love your videos. Would you please do a video about named pipes? Example: one searcher thread, and multiple worker threads that send data to the searcher thread or process.

    • @phizc
      @phizc Před rokem

      Named pipes is a heavy OS construct.. Use it for communication between processes or app domains, not between threads in a single program. It'll work, but it's like using a 10 ton truck for moving a single bottle of soda.

  • @Tunichtgut789
    @Tunichtgut789 Před 2 lety +1

    Nice

  • @danielscott6592
    @danielscott6592 Před 2 lety +2

    "Born in 420" 🍁 Excellent video Nick!

    • @KibbleWhite
      @KibbleWhite Před 2 lety

      69, just a number lol ( czcams.com/video/iqbgXgrEB4M/video.html )

  • @DevonLehmanJ
    @DevonLehmanJ Před 2 lety +13

    In some cases I feel like deconstruction can cause other problems. If you deconstruct record Book(name, isbn) to var (name, isbn), but then later decide to re-order the deconstructor, you'd break all the code doing that deconstruction with no compiler warnings or errors. If you just worked with the Book object with it's Book.Name and Book.Isbn properties this would never happen.

    • @Robert-G
      @Robert-G Před 2 lety +3

      yes, that'd why I'm hesitant to use it...
      There's stuff where it is safe, like keyvaluepair. But I even put parameter names in if the type is a common type, just to be sure no body effs it up...
      btw: it is really cool for switch expressions, but still hesitant

    • @blaarkies
      @blaarkies Před 2 lety +1

      This comparison feels wrong. It would be fair to compare it to code that extracts the values into different variables, one line at a time, and see that code cause the same issues you describe. But comparing it to code that never extracted the values at all, isn't even the same thing, it is just saying that values should never be extracted because of this issue you described?

    • @Jamiered18
      @Jamiered18 Před 2 lety +2

      Same can happen with tuples

    • @Grimlock1979
      @Grimlock1979 Před 2 lety +3

      This is one of the pitfalls, especially with dates. What if you expect (day, month, year) but the Deconstruct says (year, month, day). Oops.

    • @sara-hc7wb
      @sara-hc7wb Před 2 lety +2

      Take it as encouragement to overcome the bad habit of using primitives for everything and create more types! Help the compiler help you!

  • @Delphi80SVK
    @Delphi80SVK Před 2 lety +8

    Nick, can you make video comparing structs, records and record structs? It can be interesting theme.

    • @nothingisreal6345
      @nothingisreal6345 Před 2 lety +1

      yeah and don't forget classes and stackalloc ...

    • @Delphi80SVK
      @Delphi80SVK Před 2 lety

      He already does that video - czcams.com/video/9v6RENPk5iM/video.html

  • @JohnKerrashVirgo
    @JohnKerrashVirgo Před 2 lety +4

    Can you explain the = default!; feature on the FullName? I have not seen that syntax before.

    • @DisturbedNeo
      @DisturbedNeo Před 2 lety +5

      The string is being initialised to its default value, which is null for reference types.
      However, the compiler complains because a non-nullable property is being assigned null. To get around that, the null-forgiving operator (!) is used to tell the compiler “it’s ok, this value definitely won’t be null when I use it, trust me, I got this.”

    • @frotes
      @frotes Před 2 lety +2

      Default keyword is an explicit declaration of assigning the default value for a given type to a variable. So string is null here, book false, int would be 0, objects are null, etc.
      ! Is to get around the nullable check warnings

    • @JohnKerrashVirgo
      @JohnKerrashVirgo Před 2 lety

      Thx. Ngl, not had a use case for the null forgiving operator yet

    • @phizc
      @phizc Před rokem +1

      @@JohnKerrashVirgo simple. Just add enable to the PropertyGroup in the project file. After the 100th warning about field or property being null, you'll probably start using the ! too 😁

  • @nielsSavantKing
    @nielsSavantKing Před 2 lety

    whoo. Very nice. Of course JavaScript has already de Destructering. I didn't knew C# has it now too :)

  • @zebcode
    @zebcode Před 2 lety

    TypeScript does this so much better no need to declare a destructor method. It just feels like this is overkill.

  • @katjejoek
    @katjejoek Před 2 lety

    I just ran a small benchmark test. Having an explicit deconstruct method that returns a tuple (which is easy to deconstruct) is faster than using the suggested method here. Of course, it's just nanosecond stuff.

  • @matrixlukan
    @matrixlukan Před 2 lety

    That was awesome !!!
    Can you please make a video on following topics:-
    1. yield
    2. Asynchronous stream (video streaming)
    Thanks in advance

  • @ciberman
    @ciberman Před 2 lety +1

    Do you have any video about touples? I'm always worried if the touple I'm creating is going to allocate in the heap in performance critical scenarios

    • @phizc
      @phizc Před rokem

      If you use Tuple, then it's on the heap. They're classes.
      If you use
      (string name, int age) GetPersonInfo(...)
      it acts like a struct. They're basically ValueTuple but with a bit of compiler magic throw in.
      If it's a class member it'll be on the heap along with the rest of the data of the object, but if it's a method variable it will be on the stack. They can also be a member of a struct, in which case it'll be wherever the struct resides.

  • @xdjiijii6543
    @xdjiijii6543 Před 2 lety

    Cool to watch those new features but in the same time stuck to 7.3 at work lol

  • @Jocker88
    @Jocker88 Před 2 lety +1

    I need to ask, I have seen all the videos on this channel this year.
    How do you learn all these useful little things?
    I am in C# only since January, I know I need to learn a lot every day, but these tips aren't in other videos or books that I am reading.
    How do you learn all these magic codes?
    Thank you to share, I appreciate a lot your content, I will happy when I will buy your course :) (it's a present :P)

    • @nickchapsas
      @nickchapsas  Před 2 lety +8

      I follow the published notes for each language release or framework patch/version and I try them out.

    • @dhkatz_
      @dhkatz_ Před 2 lety +2

      I learned the same sorts of things about JavaScript just by writing a lot of little projects. You come across libraries and examples from others that might have little tricks you didn't know. Also as Nick said, follow the changes to your language.

    • @phizc
      @phizc Před rokem +1

      Don't worry.. I've been using c# for more than 20 years, and I always learn new stuff. The fact that there's new features every year keeps it interesting 😀

  • @leonardomoreno23
    @leonardomoreno23 Před 2 lety

    C# became into JS that fast I didn't see it coming.

  • @renynzea
    @renynzea Před 2 lety +5

    This would be a great feature if they made it a feature of the language, where it automatically took a deconstruction like "var (first = FirstName, last = LastName) from person" and converted it under the hood to a typical "var first = person.FirstName; var last = person.LastName". Otherwise 2 things happen: 1) When you refactor code, you could end up with naming inconsistencies, and 2) As others have pointed out, if it uses a method and the parameter order changes it could swap the values into the deconstructed parameters and you would never know it. Operator ordering is why I tend to prefer passing a single complex type for arguments to methods that require multiple arguments these days. Its a pain, but fewer issues when refactoring.

    • @tomekbednarek2672
      @tomekbednarek2672 Před 2 lety +4

      Yeah, I'm really surprised by how flawed this feature is. 1. A method with a magic name is required. 2. The original class is supposed to know which vars the calling code would be interested in? 3. Writing extra extension methods only for the sake of this? Nah, I'm still not planning to use that. MS should really have a look at JS about how to do it. But yeah, the prop naming convention is different from local var naming convention. We are doomed!

    • @bass-tones
      @bass-tones Před 2 lety +2

      I don’t really see the value in this feature either in cases where you need to write your own code for the deconstruction. However, all of these problems are avoided in record types, which generate the deconstructor for you, which is where the feature feels a little more sane.

  • @granmasterlincoln
    @granmasterlincoln Před 2 lety

    born in 420, this one never gets old

  • @matthewblott
    @matthewblott Před 2 lety

    Wow. I've been coding C# almost since it came out and I didn't know about this. Which version was this first in?

    • @pilotboba
      @pilotboba Před 2 lety +1

      C# 7 I think. Same version tuples came out iirc.

    • @matthewblott
      @matthewblott Před 2 lety

      @@pilotboba 👍

  • @jalia1998
    @jalia1998 Před 2 lety

    Hello, when you deconstruct a class does it dispose the class at the same time?

    • @Grimlock1979
      @Grimlock1979 Před 2 lety +1

      No, it has nothing to do with disposing. It is only about assigning some values to a bunch of variables.

  • @queenofpain6483
    @queenofpain6483 Před 2 lety

    Dude I’m exactly 6 days older than you but skill wise I feel like you are 6 years older than me!

  • @elfanarion
    @elfanarion Před 2 lety

    What does default! do? Default for string would be null?

  • @Couper44
    @Couper44 Před 2 lety +5

    What does "string FullName {...} = default!" means?

    • @nickchapsas
      @nickchapsas  Před 2 lety +5

      It basically tells the compiler "don't worry I know I don't have a value for it right now, but assume that it's not null because I will provide a not-nullable string when i initialize it"

    • @arkord76
      @arkord76 Před 2 lety +1

      default represents the default value of a type. For string = null, for int = 0. public string FullName { get; init; } = default! is a immutable property and you can assign any value except null.

    • @nickchapsas
      @nickchapsas  Před 2 lety +1

      @@arkord76 You can still technically assign null, the compiler by default will only warn. It translates to "The non-null default value for this type"

    • @punkerIII
      @punkerIII Před 2 lety +1

      What is the name of this feature? "default!"

    • @arkord76
      @arkord76 Před 2 lety

      ​@@nickchapsas Yes, you right. I realized it after I tested it. Thanks for the clarification.

  • @nothingisreal6345
    @nothingisreal6345 Před 2 lety

    Didn't even know it existed. Nich to have - but not really essential.🦄

  • @karthiksrivatsa8243
    @karthiksrivatsa8243 Před 2 lety

    This is so good. But 420 & 69 is funny though 😂

  • @poipoi300
    @poipoi300 Před 2 lety +1

    I understand the potential usefulness, however I think this could easily lead to code obfuscation. If you'd like to create variables to copy details into, I think it's better that the source variables are explicitly referenced. If I'm reading code, I don't want to have to step into whatever "nick" is to know that it's simply returning some unmodified data (especially when using var), and not formatting it or performing any other kinds of operations. I think something like:
    var (firstName, dob) = (nick.firstName, nick.dob);
    is more readable. Even better, don't copy memory if you don't plan to make modifications or operations on it and the data isn't expected to change while you're performing your operations. If you simply want to write the first name and date of birth in a string, access the object fields directly.

    • @tiagodagostini
      @tiagodagostini Před 2 lety

      In large code sqeuences where several of those operatiosn are repeated from severl sources that leads to smaller and cleaner code. Somethign that is not clearer with ONE execution might be the most clear way when you are doing it 10 times.

    • @poipoi300
      @poipoi300 Před 2 lety

      @@tiagodagostini Yeah I agree that it can be useful and neater, but in most cases not. Just another tool to keep into the back of your head.

  • @MaurizioVerde
    @MaurizioVerde Před 2 lety

    Cool! You are born exactly 20 years after me! 20/04/1973 :D
    :'(

  • @rik0904
    @rik0904 Před 2 lety

    wait what happens with instance of this object after deconstruction ? do we have two instance of this element in memory ?

    • @janne_kekalainen
      @janne_kekalainen Před 2 lety +1

      Nothing changes since the deconstructor only reads from instance.
      It's basically the inverse of a constructor.
      Instead of taking in x, y, and z and spitting out something, it takes in that something and returns x, y, and z.

  • @thursday270
    @thursday270 Před 2 lety

    Jesus, I don't know C# anymore, haha. Thanks!

  • @dgschrei
    @dgschrei Před 2 lety +21

    Unless there is some serious IDE support that will tell you what deconstructors exist and tells you what to actually expect from the values you get back (i.e. Actual API documentation) I really hope this feature doesn't take off because it's just another level of hidden magic complexity that makes code harder to read and understand. Now you have code that looks like an assignment and instead really is a method call. And if your video is to be believed, the only way to find out what method the code actually jumps into is to run the code through the debugger. That sounds like development hell to me. And for what? So that you can be so UNBELIEVABLY lazy that a book.Deconstruct(out var title, out var isbn) was just too much to ask for. Seriously?
    And with the automatically implemented deconstructors in record types it just becomes plain evil and a giant problem. Say we remove the isbn from the book record and instead replace it with a second string property that contains the author.
    In normal code that actually calls the property all uses of the isbn property will break (because of course that property no longer exists) and the compiler will tell you everything you need to fix.
    If you use the deconstructor: well bad luck for you all usages just continue to work because both the number of arguments and the data types are identical. It just so happens that all your code that expects an ISBN is now being fed author names and stuff randomly breaks. If you're very lucky by actually crashing. If you're not lucky this now will pollute and corrupt your database by putting data into the wrong collums. Have fun explaining to IRS auditors why the address column in your billing table now suddenly contains your customer's email addresses instead. (you better be the God of unit testing to catch all of these)
    And the best part. The IDE has no chance of detecting this so now you have to go through all your code manually and find all the offending spots and fix them by hand. Sounds like development hell for me. Especially since this can happen to you unexpectedly if the record type you're consuming is from an external library. Update the nuget package - > everything compiles but suddenly you have seemingly random unexpected behavior. And again for what? So the programmer can be just a tiny bit more lazy?
    Code is a list of statements. They express intent. So put the intent into the statement instead of hiding it behind a bunch of roslyn pixie fairy dust. The devs that will have to clean your code up after you moved on to build the next microservice in your next contract will be ever so thankful.
    Oh and I just thought of another reason not to use it on record types. If you add another property to a record (so a purely additive change that therefore shouldn't be breaking) that now becomes a breaking change and forces you to touch every spot where that deconstructor was used. Yay....

    • @bennettmagy8215
      @bennettmagy8215 Před 2 lety +6

      Totally agree. Order and type are not sufficient things to deconstruct on and leave a lot of chances to flip args. Feature would be a lot safer and readable if you had to deconstruct based on field names (like you can in js) rather than based on field order.

    • @vasiliychernov2123
      @vasiliychernov2123 Před 2 lety +1

      I had absolutely the same thoughts.

  • @dhkatz_
    @dhkatz_ Před 2 lety +2

    I love desconstruction/destructuring but I really don't like having to write a method for it. Should just be a part of the language that works. Even C++ did it better in my opinion. Although the crown has to probably go to JavaScript and/or Kotlin in that regard.

    • @willinton06
      @willinton06 Před 2 lety +1

      Feels weird to give JavaScript credit for anything but yeah, it’s destruction is definitely top of the chain

  • @chesterapavliashvili1533

    I think they should make Deconstruct as a keyword for methods like virtual or something

  • @toastyshrimp1882
    @toastyshrimp1882 Před 2 lety

    This feels quite beyond me currently, after the first few lines with a init setter and default, and then object creation without a constructor? all of this threw me for a loop as I've never seen anything like it. I swear, every time I feel like I'm finally getting the hang of programming I'm shown time and again I have absolutely no clue what I'm doing.

  • @siriusblack9999
    @siriusblack9999 Před 2 lety +1

    i'm personally not a fan of "magic phrases" in programming, as i feel it's like language-sanctioned stringly typed programming,
    i won't be using this technique for that reason alone (instead, if i wanted to achieve this effect i would create a separate function that returns a tuple and must be called explicitly)
    My problem here isn't the concept of deconstructing the object, but rather the fact that this function called "deconstruct" is used as if it was an implicit cast operator, these two things are not the same which breaks your (or at least my) ability to logically reason about what's happening,
    to someone who doesn't know about this special case, you have a named function that's seemingly never referenced, and an implicit cast to a tuple that doesn't seem to have an associated implementation.
    you HAVE to know that this "magic phrase" exists, and how it works in order to understand any code that uses this, that's rude (IMO) and a code smell

  • @andzagorulko
    @andzagorulko Před 2 lety +1

    I know it will be a bad idea to have several deconstuctors, but how is overloading handled with such patterns and can you even have 2 of them for 1 class?

    • @pilotboba
      @pilotboba Před 2 lety

      public void Deconstruct(out string firstName, out string lastName)
      {
      firstName = FirstName;
      lastName = LastName;
      }

      public void Deconstruct(out string firstName)
      {
      firstName = FirstName;
      }

  • @tobilinz_
    @tobilinz_ Před 2 lety +2

    what does the default! thing mean? I know that default assigns a value to its default state but I can't figure out what the exclamation mark means.
    Edit: and what does the :Mdd mean?

    • @alphaios7763
      @alphaios7763 Před 2 lety

      ! is a .NET 6 thing I believe and from what I’ve seen so far, it seems to tell the compiler that this value won’t be null so that it doesn’t warn you later on. Please someone correct me if I’m wrong.
      :Mdd is like calling dateOnly.ToString(“Mdd”) where M represents month (lowercase m is for minutes) and d represents day. d will not add trailing zeros if day is single digit / < 10 (e.g. 09), but dd will

    • @nickchapsas
      @nickchapsas  Před 2 lety +1

      It’s not a .NET 6 thing. It’s been in the language since C# 8. It tells the compiler that this value is definitely not null. In that context it just tells the compiler to stop complaining for an uninitialised string that isn’t marked as nullable

    • @tobilinz_
      @tobilinz_ Před 2 lety

      @@nickchapsas oh ok. But I don't quite understand what the :Mdd does. It is a shorthand for calling ToString.
      But what is it exactly? Is it a method reference? It reminds me of the Java Syntax MyObject::myMethod.

    • @Grimlock1979
      @Grimlock1979 Před 2 lety

      @@tobilinz_ :Mdd is string formatting. The M stands for the month number and dd stands for the day. When you look at the output, it says: "born in 420", month 4 and day 20.

    • @tobilinz_
      @tobilinz_ Před 2 lety

      @@Grimlock1979 so the : means .ToString? Let's say I create a class. Can I convert it to a string using this too?

  • @Crown0815
    @Crown0815 Před 2 lety

    this is exactly what i needed 2 days ago! you are two days to late ;)

  • @shelbytimbrook2095
    @shelbytimbrook2095 Před 2 lety

    I'm finding it hard to come up with a scenario where I'd actually use deconstruction.
    These things give me that uneasy feeling you get when you know something is a code smell, but can't quite articulate why yet.

  • @raztubes
    @raztubes Před 2 lety

    So is the deconstruction method name reserved, then? Like when defining the extension method, for example.

    • @Grimlock1979
      @Grimlock1979 Před 2 lety

      Yes, it is pattern based. When you create a method with out parameters and you name it Deconstruct, the compiler wil recognize it and you will automatically be able to use the syntax with parenthesis.
      Some other things are pattern based as well, like the Dispose() method. You don't need to implement IDisposable in order to use the 'using' syntax. Same with foreach and GetEnumerator().

    • @raztubes
      @raztubes Před 2 lety

      @@Grimlock1979 Since when? I did not know C# did duck typing like that, will have to check it out.

  • @jaybretherton6246
    @jaybretherton6246 Před 2 lety

    What is really confusing me is why this is set up using out parameters when it seems like it would be far more obvious to return a tuple? is there a reason for this do you know?

  • @tobiasjohansson1256
    @tobiasjohansson1256 Před 2 lety

    Could you please also post your videos on LBRY?

  • @KoScosss
    @KoScosss Před rokem

    I'm so mad that they have you define Deconstruct method and not just access public members via code lowering.
    Js does it right. No defining Deconstruct for each desired combination. No _ to discard unneeded data.
    The only great thing about c# way is extensions of 3rd party types - that's pretty neat.

  • @anthonypark9158
    @anthonypark9158 Před 2 lety

    What does that "!" do after "default"?

    • @KibbleWhite
      @KibbleWhite Před 2 lety

      In the second example down, hope that helps: docs.microsoft.com/en-us/dotnet/csharp/nullable-references#nullable-variable-annotations
      Known as the null forgiving operator: docs.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving

    • @Grimlock1979
      @Grimlock1979 Před 2 lety +2

      Also known as the dammit! operator.

  • @ronaldestacion7114
    @ronaldestacion7114 Před 2 lety

    When was Deconstructors added?

    • @Grimlock1979
      @Grimlock1979 Před 2 lety

      At the same time tuple syntax was added. C# 7.

  • @Bolt219
    @Bolt219 Před 2 lety +1

    Clean? - Maybe. Readable? - Definitely not.

  • @user-zk5ym9ut1j
    @user-zk5ym9ut1j Před 2 lety +1

    This syntax is mostly confusing because it's like tuple and seeing it you'll slow down, so pls avoid it in your production code at all

  • @fatdumbledore1337
    @fatdumbledore1337 Před 2 lety

    born on 420 and his "random" number is 69.
    I can see where u are going :D
    Nice vid !

  • @VaragornX
    @VaragornX Před 2 lety +2

    I don't know where I would need/use this. As with the tuples its a nice feature, but it just feels like bloating the language. Probaply something that I will try to use once or twice and then forget about it.

    • @nickchapsas
      @nickchapsas  Před 2 lety +2

      Key-Value pairs is where I always deconstruct because it makes it more readable IMO

    • @Dustyy01
      @Dustyy01 Před 2 lety

      Yea kvp with foreach is a rly good use case imo. I always use that

  • @ThiagoZeroUm
    @ThiagoZeroUm Před 2 lety

    Deserved my like for the deconstruction, but deserved my sub for the 420/69.

  • @ddxjon
    @ddxjon Před 2 lety

    it's just a number, a magic number 🙊

  • @Kingside88
    @Kingside88 Před 2 lety

    Now I know what deconstrusion is. But nobody would understand if I would start using it. Really not common this feature

  • @bloggrammer
    @bloggrammer Před 2 lety

    Does the method name 'Deconstruction' matters?

  • @jonaskowalczyk_
    @jonaskowalczyk_ Před 2 lety

    You were born on same date as me, except I was born in 1998.

  • @benjaminclehmann
    @benjaminclehmann Před 2 lety

    Still not sure why they didn't call it unpacking and avoid the confusing name.

  • @cocoscacao6102
    @cocoscacao6102 Před 2 lety

    I have a hunch that 69 is Nick's favourite number. It's in every example revolving around ints

  • @JarleXXX
    @JarleXXX Před 2 lety

    I hate that C# requires a deconstructor method. This should just have worked out of the box based on conventions

  • @psdmaniac
    @psdmaniac Před 2 měsíci

    Step in the wrong direction. A step from magic, unicorns, anonymous object everywhere and JavaScript 💩

  • @fat-freeoliveoil6553
    @fat-freeoliveoil6553 Před 2 lety +1

    Interesting video but I honestly don't find this very useful.
    1) It only really works with small data types because if you were to use large data types, you'll be doing a lot of discarding, which will just make your code messier.
    2) It requires you to know the order of parameters, and because of how it's laid out, the IDE also doesn't give any assistance. This is likely going to lead to a lot of code lookup.
    If you can't figure out what the code is doing by simply reading it, then you're doing something wrong imo.

  • @snansahmarov1524
    @snansahmarov1524 Před 2 lety

    08:44 😀

  • @SuperLabeled
    @SuperLabeled Před 4 měsíci

    I don't like it because you have to know the element in the correction position otherwise you could set your variables to the wrong thing and it's not entirely obvious when reviewing code that the variables have been swapped.

  • @OllyWood688
    @OllyWood688 Před 2 lety

    Generic Decostructors + Pattern Matching = Code-equivalent of erotica

  • @akuskus
    @akuskus Před 2 lety

    Now I know which feature I will avoid using.

  • @talldutchguyk8247
    @talldutchguyk8247 Před 2 lety

    Peak comedy

  • @TheNorthRemember
    @TheNorthRemember Před rokem

    this makes code complex in my eyes

  • @deboayangbile1689
    @deboayangbile1689 Před 2 lety

    I have used them from time to time. I thought they were tuples. Are they?

    • @nickchapsas
      @nickchapsas  Před 2 lety

      The deconstruction creates Tuples yeah

    • @deboayangbile1689
      @deboayangbile1689 Před 2 lety

      @@nickchapsas I thought as much. Been pretty much using them for a while now but always referred to them as tuples never as type deconstruction

    • @code8986
      @code8986 Před 2 lety

      @@deboayangbile1689 The object is deconstructed *into* a tuple.

  • @cfehunter
    @cfehunter Před 2 lety

    So it calls a completely undedcorated method with no interface restrictions?
    It's useful I suppose, but it's really out of place compared to the rest of the language.

  • @Spirch
    @Spirch Před 2 lety

    how about 42? you have to ask the question!

  • @shomari169
    @shomari169 Před 2 lety

    you seems to prefer Rider over VS any reasons why

  • @tiagodagostini
    @tiagodagostini Před 2 lety

    The name does not make sense at all with the purpose. It is neat (in C++ I would have to write a more complex member declaration (a conversion operator to a tuple), but they coudl have found a better name for that.

  • @sirdondaniel
    @sirdondaniel Před 2 lety

    I like your numbers: 420, 69.

  • @DoorThief
    @DoorThief Před 2 lety

    :Mdd Sneaky 😂

  • @DEVDerr
    @DEVDerr Před 2 lety

    Well... comparing it to f.e. JavaScript/TypeScript deconstructing, it's reaaaally reallyyyyy weird and unreadable syntax. Like...
    How on the first glance am I supposed to know that some method called Deconstruct (which is not even marked as reserved keyword in IDE lol... so I can assume that it could be normal method of some class), would be connected to this magic syntax
    (var fullName, var dateOfBirth) = nick; (where this looks like method call without it's name mentioned... another wtf)
    Discarding is also weird
    It's super super weird