Collection Expressions in .NET 8

Поделиться
HTML-код
  • Опубликовано: 24 июл 2024
  • In .NET 8, we are now able to initialize lists and arrays cleanly using the new Collection Expressions syntax. Let's see how they work in this 10-minute training video.
    Full Training Courses: IAmTimCorey.com
    Source Code: leadmagnets.app/?Resource=Col...
    Mailing List: signup.iamtimcorey.com/

Комментарии • 63

  • @georget10i
    @georget10i 7 месяцев назад +8

    This is a really great addition in my opinion. Unifying initialisation for collections is a really good idea. You can do range operations on it too.
    Example:
    int[] numbers1 = [1, 2, 3, 4];
    int[] numbers2 = [6, 7, 8, 9];
    List numbersConcatinated1 = [..numbers1, 5]; // if looped and printed will result in 1, 2, 3, 4, 5
    List numbersConcatinated2 = [..numbers1, 5, ..numbers2]; // if looped and printed will result in 1, 2, 3, 4, 5, 6, 7, 8, 9

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +1

      Yeah, that is pretty cool.

  • @kurtrichter5500
    @kurtrichter5500 7 месяцев назад +8

    I've been coding in C# 12 on a personal project and I learned that you also can initialize a dictionary the same way. For example:
    Dictionary dictionary = [ ];
    Turns out this even works when you have a custom class that inherits from dictionary and has a constructor with logic in it. It still calls the parameterless constructor! For example:
    public class CustomDictionary : Dictionary {
    public CustomDictionary() {
    Add("someKey", "someValue");
    }
    }
    Then calling
    CustomDictionary customDictionary = [ ];
    will have called the constructor and be populated.

    • @purplepixeleater
      @purplepixeleater 7 месяцев назад +1

      It works for hashsets as as well :)

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +2

      Yep, it should work for most, if not all set types. I do believe there are some exceptions, though.

  • @evangreavu9621
    @evangreavu9621 7 месяцев назад +2

    Every complaint I have with C# eventually gets fixed. I LOVE THIS LANGUAGE!!

  • @SagharMax
    @SagharMax 6 месяцев назад

    It is straightforward now. I like it. Thank you.

  • @swordblaster2596
    @swordblaster2596 7 месяцев назад +2

    Yeah, it's fine. Looks a bit weird at first, but makes sense. An actual clean improvement!

  • @RogueCoder7505
    @RogueCoder7505 7 месяцев назад +6

    Gotta love how c# is becoming more pythonic😍

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +10

      Every time the language changes, people point out how it is becoming like another language. On this one, I've also heard Typescript (which is a Microsoft language, by the way). Languages tend to look like each other because they are trying to express similar concepts.

    • @purplepixeleater
      @purplepixeleater 7 месяцев назад

      Well c# is much older than ts so it points at ts borrowing many concepts from cs but never paying homage lol @@IAmTimCorey

    • @itsallgravy_9437
      @itsallgravy_9437 7 месяцев назад

      @@IAmTimCorey I agree, programming languages are often convergent through maturity - as you say they're all trying to do similar things in a way that is 'most natural'. To diverge massively in that case would be to either be trying to acheive a completely new approach, or just massively argumentative and looking for a fight.

    • @garya1809
      @garya1809 5 месяцев назад

      This is how Swift handles declarations and initialization too.

  • @alialshreef2874
    @alialshreef2874 4 месяца назад

    Thanks Tim

  • @majiddadollahi6654
    @majiddadollahi6654 7 месяцев назад

    This is a very good Idea.

  • @holger_p
    @holger_p 7 месяцев назад

    So we can forget about Array.Empty() I guess, I hope that's used under the hood now.
    "simpler" often means, giving up control, and let others decide.

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад

      Forget about it? No. You can still use it if you want and you can use it in earlier versions of .NET/C#. However, this syntax will choose the most efficient way of initializing the set for you.

    • @holger_p
      @holger_p 7 месяцев назад

      @@IAmTimCorey Sure I can, just saying the need to use it, is gone. But we have to trust, it is "most efficient". We give up control.

  • @dsx7517
    @dsx7517 7 месяцев назад +6

    Maybe I'm just too old, but I can't say I am a big fan of changes like this one.
    "Because it looks ugly?" That's a very subjective reasoning. Personally, I don't see anything wrong or ugly with the current syntax.

    • @user-cl8lf1wm8b
      @user-cl8lf1wm8b 7 месяцев назад

      I agree with you about 'ugly' part, but I also agree with the point in video about simplified initialization. I sometimes forget about the syntax of array initialization too. That part is a good change for the language

    • @lolyasuo1235
      @lolyasuo1235 7 месяцев назад +1

      I dont like this too. Too "scriptish" for my coding style. We do not want C# to become a scriptish language :). If C# ever become a scriptish-like language then why to stand in .NET ecosystem?
      This change is ugly and confusing.

    • @purplepixeleater
      @purplepixeleater 7 месяцев назад

      you definitely just learned how to use collections in the first place lol@@lolyasuo1235

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +3

      They did this for simplicity. We are already using [] in pattern matching as well, so there is already precedent. The current syntax has the issue of being different for different types of sets. That is inconsistent and annoying, especially if you change types. Also, there can be various ways of doing things. This new syntax ensures that you always initialize the set in the most efficient manner possible.

    • @trevordennis
      @trevordennis 7 месяцев назад +1

      I definitely prefer to write things out explicitly instead of using shortcuts like this. It might be less characters, but you have no idea what "[ ]" is when looking at the code later. You have to hunt down the method to see what data type it turns out to be. It you had just typed "new List()" you would know immediately. Good code should be self-documenting.

  • @alexnemeth3680
    @alexnemeth3680 7 месяцев назад +5

    isn't this a C# 12 feature rather than a .NET 8 feature?

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +2

      Yep, you are right. You can technically use this feature in .NET 7 if you use a flag.

  • @marcusreinicke
    @marcusreinicke 7 месяцев назад +2

    Hi Tim, you always celebrate the innovations. But in many cases Micosoft is breaking more and more at the moment.
    What happens with an instruction
    var Test =[1,2,3,4,5];
    I hope it doesn't work, because then what type do we have here?
    When var was introduced it was hyped, now we are taking a step back again.
    Additionally a synthax that will make the code harder to read

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +2

      That syntax doesn't work because the type cannot be inferred. That has been the case well before this new collection expression syntax was added. Personally, I wouldn't mind if they did make it work, though, and just infer that you meant List. But for now, they haven't done that. At the end of the day, how does this hurt you? You seem upset by something that you aren't sure would work (and doesn't). Why not just learn about the new capabilities instead of getting upset at phantom problems?
      As for the syntax being harder to read, what are you talking about? Do you mean that int[] test = [1,2,3]; is hard to read? Or are you talking about how var i = 1; is hard to read?

    • @marcusreinicke
      @marcusreinicke 7 месяцев назад +1

      @@IAmTimCorey Hi Tim, I've been following you for a long time and you know that I think a lot of you. I have already learned a lot from you.
      It's nothing personal, I like to question things.
      First of all, it doesn't matter whether square brackets or curly brackets.
      That's not a problem and it doesn't matter.
      I see the problem in such an instruction:
      var test = Foo([]);
      This comes close to this statement.
      var test = Foo(new(), new(),new());
      This statement is nice to write, but scary to read.
      Why am I deliberately passing an empty list or array without a type?
      The only thing I can think of off the top of my head would be UnitTests.
      It might not be so annoying there. I'm not sure.
      Even without Intelisense, I know that it is a contract of IEnumerable.
      But for reading, for example
      ProcessingBill.PrintBillPositions(positions);
      is clearly better than
      ProcessingBill.PrintBillPositions([]);
      I would be interested to know what a Robert C. Martin thinks of such constructs.

  • @halivudestevez2
    @halivudestevez2 6 месяцев назад

    I would be happy, if we could initialize member scoped Lists or Arrays by a function, or query.
    I don't see the point for these expression thing, but ok. Cleaner. Nice.

    • @IAmTimCorey
      @IAmTimCorey  6 месяцев назад

      Can you clarify what you are asking for?

  • @TheUnknown1709
    @TheUnknown1709 7 месяцев назад

    So can we now officially declare the death of var
    var list5 = [1, 2, 3];
    There is no target type for the collection expression.

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад

      This isn't a great take. You can't use var when the type is not knowable. That's always been the case. That doesn't mean var is dead. It just means the existing limitations are still in place.

  • @MrFoghorn111
    @MrFoghorn111 7 месяцев назад

    Will this work with dictionaries?

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +1

      Yes, it will. It works with almost every set type, at least for the initialization of an empty set.

  • @purplepixeleater
    @purplepixeleater 7 месяцев назад +1

    These have cleaned up my code so much and I didn't even know it was an option until my ide told me...

  • @keyser456
    @keyser456 7 месяцев назад +13

    One more convention/syntax to have to remember. I do believe this new way will be easier for new-comers, but in the real world they'll still have to learn the old style in case they run into it. You don't have to learn just one way of doing something, you have to learn 27... err... make that 28 different ways.

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +6

      I can't see how [] isn't objectively better than new {} or new()[] or whatever that specific set requires. Yes, that means if you are doing work in an older syntax, you will have to use the old way. That's not something Microsoft can change. But they can change for the future. Not changing because there is already a way means no progress ever gets made. By that logic, we should have stuck with WinForms and WebForms.

    • @keyser456
      @keyser456 7 месяцев назад

      ​@@IAmTimCorey I don't believe I made an argument that it's not better. It is imo, but it's in addition to the other syntax(es). Whenever you encounter *any* of the growing # of conventions for every aspect of C# anywhere in any projects, including all the old ones from versions past, you have to be able to recognize them, and in many cases work/remain with that syntax in that codebase.
      I was working with switch expressions w/ relational patterns, properties, and combinators this last week. While extremely powerful, that has practically turned into its own language over the past several C# versions! I haven't run into that in any existing production codebases yet (no, honestly, I really haven't), but being the proactive developer we are (right, right!?), we have to learn all of this and know all of this (old, new, and everything in between) in case we run into it. The breadth of knowledge required just on syntax/convention alone is becoming more daunting with every version. I'm worried about introducing some of these newer conventions for fear all the other devs, junior up through the most grizzled senior devs, ̶m̶a̶y̶ ̶n̶o̶t̶ ̶b̶e̶ probably are not familiar with all of them.
      More and more you see new code and wonder "is that even valid C#?" only to go look it up, and sure enough, new syntax! Is there a plan to somehow merge these all into "the best way" at some point? Maybe deprecate or make older conventions obsolete at some point? I'm all for progress, but let's clean up after ourselves and try to make life easier for future generations of C#/.NET devs. :)

    • @ivanvincent7534
      @ivanvincent7534 7 месяцев назад +1

      Progressing from Webforms to Blazor is not about syntax. The previous comment remains valid about time and resources to learn new ways to do the same thing.

    • @mynameisshadywhat
      @mynameisshadywhat 7 месяцев назад

      ​@@IAmTimCorey WinForms is in .NET 8 and has been getting new features/improvements in every recent version of .NET?

    • @itsallgravy_9437
      @itsallgravy_9437 7 месяцев назад +1

      Ultimately it's a syntactic sugar for the same raw code. If it's successful it will become common parlance, otherwise it will fall out of use. How many of use use $"{variable} is new" over string.Format("{0} is new", variable) without even thinking about it? (I actually had to pause on the string.Format!). Likewise how many of us still use var blah = new Somthing() versus Something blah = new() ? How many of us started in Net 1.0? how many of us want to go back?

  • @yasminarab1353
    @yasminarab1353 7 месяцев назад

    They try to make c# and typescript identical

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +2

      Every time the language changes, people point out how it is becoming like another language. On this one, I've also heard Python. Languages tend to look like each other because they are trying to express similar concepts. By the way, not that it matters, but Typescript is a Microsoft language.

    • @obinnaokafor6252
      @obinnaokafor6252 7 месяцев назад

      C# team actually started the development of Typescript

  • @CuriousEvidence
    @CuriousEvidence 7 месяцев назад

    This is not a .NET 8 enhancement; the title is misleading unfortunately. It's a new feature of the C# language.

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад

      True. It came out with .NET 8 and only works natively with .NET 8 (although it can be back-ported a bit using a flag).

  • @namelastname4077
    @namelastname4077 7 месяцев назад

    Can't see why this is worthy of a video. You can now do it. Ok.

    • @IAmTimCorey
      @IAmTimCorey  7 месяцев назад +4

      Because there is more to it than just saying "use [] to initialize arrays".

    • @holger_p
      @holger_p 7 месяцев назад

      Some prefer a "What's new article", others prefer somebody talking and showing.