The New Inline Arrays of C# 12 Are Awesome, But…

Sdílet
Vložit
  • čas přidán 16. 07. 2023
  • 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 introduce you to a new feature coming in C# 12, called Inline Arrays. It is a new technique for creating fixed-size arrays, but what's interesting about it is that Microsoft seems to be adding it mainly for them to use.
    Proposal: github.com/dotnet/csharplang/...
    Workshops: bit.ly/nickworkshops
    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 • 87

  • @DotNetCookbook
    @DotNetCookbook Před 10 měsíci +58

    What is really needed is a performance comparison with stackallock and Span.

    • @nickchapsas
      @nickchapsas  Před 10 měsíci +47

      I'm waiting for .NET 8 to be out out to get the most accurate results on this

    • @warrenbuckley3267
      @warrenbuckley3267 Před 10 měsíci

      Yeah I really want to see this comparison as well.

  • @nvmuzrowrihk
    @nvmuzrowrihk Před 10 měsíci +27

    This is very neat for situations where you need a fixed size array as a field but don't want a heap allocated array. The current Guid implementation is a great example. Right now, it just has multiple different fields to get make the struct a fixed size.

  • @EtienneFortin
    @EtienneFortin Před 10 měsíci +31

    Fixed size array as we have in C/C++. I think it's a good feature, not just for Microsoft, for high performance scenarios. It allows for using C# in more performance centric things. I wish they'll change the syntax though.

    • @alluseri
      @alluseri Před 10 měsíci

      how so

    • @EtienneFortin
      @EtienneFortin Před 10 měsíci

      @@alluseri how so about the performance scenario or about the syntax? For the performance scenario it allows for having a fixedblock of memory that you can play with without the overhead of a "classic" array. For the syntax well I think it speaks for itself. Some class with one member and some attribute... The best would be to use it like a fixed size array in C/C++ : int[10] someFixedArray;

  • @Soraphis91
    @Soraphis91 Před 10 měsíci +5

    syntaxwise, I would actually prefer something like `var array = new FixedBuffer()`

    • @Kitulous
      @Kitulous Před 10 měsíci

      unfortunately c# is not c++ and generics are runtime as opposed to compile time templates, so anything other than type names are not allowed in generics

    • @Soraphis91
      @Soraphis91 Před 10 měsíci +1

      @@Kitulous that is more a technicality. If they would like to, nobody could stop them to change that. Or make it so, the constant part is basically syntactic sugar and is compiled away, while the type part stays for the JIT.
      Allowing constants - even if only syntactic sugar - could benefit even more people that just this.

  • @diadetediotedio6918
    @diadetediotedio6918 Před 10 měsíci +12

    I think features they need also collide with features we need, C# is used in a variety of industries you know, even game engines, so these sort of things are interesting IMHO.

  • @billy65bob
    @billy65bob Před 10 měsíci +4

    If I'm not mistaken, .NET's strings have worked this way for a very long time.
    I can definitely see it being used to make certain code a lot less gross. Especially if the size can be decided at runtime (aka exactly how strings do it).
    With that said, I think it needs a bit of tweaking. Imagine something like:
    [InlineArray(10, nameof(firstArrayField))]
    public struct MyType {
    private int normalField1;
    private int normalField2;
    private byte firstArrayField; //must be the last item
    }
    EDIT: e.g. imagine you made a RingBuffer1024 struct here, and the normal fields track how full the buffer actually is, and the index to start from.

  • @jongeduard
    @jongeduard Před 6 měsíci

    I am currently exploring this thing for my learning and what already I see is 2 major differences with stackalloc.
    First of all, this thing allows strings and any other reference type to be used as array elements. So that means it's able to store managed references (which are technically just memory addresses, which take 8 bytes on a 64 system and 4 bytes on a 32 bit system) sequentially in the array as part of the current scope's allocated memory (hence the name inline).
    The second difference is that this existing allocation for the array does not have to be just a stack, but can also be the heap. So you can declare class fields as this array type. Just like any regular value type can be a field of a class.
    It's really great that they made this possible and this thing was indeed a missing feature in DotNet. The syntax to declare it is kind of weird and not so beautiful, but given it's something that you don't need in your everyday code I think it's fine.

  • @JMPDev
    @JMPDev Před 10 měsíci +6

    This is literally something I was wishing I had access to earlier today while writing a fairly optimized text mesh rendering solution.

  • @protox4
    @protox4 Před 10 měsíci +1

    This looks like it could be used for `params Span` implementation.

  • @briankesecker
    @briankesecker Před 10 měsíci

    Hi Nick. Very useful video for me. With respect to MS focusing on what they need, 1) agree that looks like what is happening, but 2) from a long-term perspective, what better proving ground than their own solutions? Working out the pain points before handing it out.

  • @asaf92
    @asaf92 Před 10 měsíci +7

    This reminds me of unsafe fixed size arrays. I sometimes really wish the compiler would have been smart enough to optimize local arrays that can't "escape" by allocating them on the stack.

  • @mehmetck
    @mehmetck Před 10 měsíci

    Really good fit for circular buffer

  • @DaddyFrosty
    @DaddyFrosty Před 10 měsíci +3

    “Might ring a bell”. Yeah I use alloca to allocate dynamic size arrays on the stack. ¿Problem?

  • @oscareriksson9414
    @oscareriksson9414 Před 10 měsíci

    I often miss a thing like that. Sure I use span when I need a quick stack array but many times I just go through them and don't actually need that whole API. Also, if you read that file before compilation, you can change the fixed size

  • @KopieOG
    @KopieOG Před 10 měsíci

    This is actually very useful, I needed that

  • @LynxofCP
    @LynxofCP Před 10 měsíci +1

    I dunno, if I understand the use case for this, then this will be absolutely magic for the backing structs for GPU shaders. It can be REALLY useful to create a fixed-size buffer in a data structure in these unmanaged situations.

  • @Crozz22
    @Crozz22 Před 10 měsíci +28

    I really wish Microsoft would focus on adding discriminated unions to C#.

    • @mikaelsyska
      @mikaelsyska Před 10 měsíci +1

      They are working on it. Things take time to get it right ...
      So I don't see the issue 🤔

  • @Crozz22
    @Crozz22 Před 10 měsíci

    Any difference if the struct is a readonly struct?

  • @ThainaYu
    @ThainaYu Před 10 měsíci +1

    I may not use it but this must be crucial for Vector and Matrix in any game engine

  • @Petzku01
    @Petzku01 Před 3 měsíci

    Hello dr. Nick!

  • @DiomedesDominguez
    @DiomedesDominguez Před 10 měsíci

    I may use it, since I work with a lot of big sized CSV files (several GBs) in the background, but I need to make some tests.

    • @phizc
      @phizc Před 10 měsíci

      You shouldn't use this for long lived large arrays, I think.
      If nothing else, the length of the array needs to be known at compile time, so unless all the csv files are of the same length, it's going to be hard to use.
      The stack is only 2MB, by default I think, so it can't be purely on the stack either, probably.

  • @Gxost14
    @Gxost14 Před 10 měsíci

    Doesn't the performance of the inline array benchmark suffer because of the big structure is returned from the benchmark method?

  • @robertbucur1256
    @robertbucur1256 Před 10 měsíci

    Thanks for great videos, how come you change Rider with Visual Studio?

    • @nickchapsas
      @nickchapsas  Před 10 měsíci +6

      I literally mention it in the first 20 seconds of the video

    • @robertbucur1256
      @robertbucur1256 Před 10 měsíci

      @@nickchapsas my bad, to be honest I focus all my attention in the beginning on the IDE. Thanks for reply

  • @djupstaten2328
    @djupstaten2328 Před 9 měsíci

    My thoughts are -- the possibility of setting a hard cap on how many elements a collection will accept is fantastic. Now, if they would only implement a where-constraint that communicates this at design time, it would be great. Not just for this novel type but for any collection. Also just give us more where-constraints in general. Limitations = creative results. Creative limitations = creative results x10.

  • @zxopink
    @zxopink Před 10 měsíci

    What's element0 and what will I get if I access it?

  • @user-zk5ym9ut1j
    @user-zk5ym9ut1j Před 10 měsíci

    Small sized arrays are actually way faster then specialized collections because of locality so data can be aggressively cached by CPU

  • @anonimxwz
    @anonimxwz Před 10 měsíci

    InlineArray can use another size? Or always must use the value written on [InlineArray(Lenght)] ??

  • @killpopers
    @killpopers Před 10 měsíci +1

    This is intresting csn see it being helpful if yiur doing Vulkan/DirectX programming in C# rather than C++ which i do sonetimes for fun

  • @user-tk2jy8xr8b
    @user-tk2jy8xr8b Před 10 měsíci

    Interesting feature, by why not introducing dynamically-sized arrays baked into classes like they have it for System.String?

  • @onionware1
    @onionware1 Před 10 měsíci

    Can you make a video about how to use COM interfaces/classes with NativeAOT? When I want to use the ITaskbarList3 with [ComImport] and [Guid("ea1afb91-9e28-4b86-90e9-9e9f8a5eefaf")], it does not work with NativeAOT

  • @LudwigvanBeethoven2
    @LudwigvanBeethoven2 Před 10 měsíci

    What is the difference between stackalloc and InlineArray? I assume InlineArray is allocated on stack otherwise where else would it be?

    • @jackoberto01
      @jackoberto01 Před 10 měsíci

      Like he mentions in the video stackalloc forces the Array to be allocated on the stack while this allows it to be allocated on the heap if there's no space left on the stack

    • @yannickurbach5654
      @yannickurbach5654 Před 10 měsíci +1

      You can only use stackalloc in a method to allocate memory in the current stackframe. Once it goes out of scope, it's gone. Basically just a local variable. InlineArray structs can be used as fields in structs and classes, returned from functions, captured in closures, etc.

  • @yufgyug3735
    @yufgyug3735 Před 10 měsíci +2

    so c# already has fixed size buffers, what is the benefit of this new feature? not requiring using unsafe keyword?

    • @yannickurbach5654
      @yannickurbach5654 Před 10 měsíci

      Fixed size buffers can for some reason only have primitive types, this will apparently support any type. Also, this will have bounds checking. Though I wish they'd just extend fixed size buffers rather than introducing yet another way to do almost the same thing.

  • @Tsunami14
    @Tsunami14 Před 10 měsíci

    Couldn't they just change it so that if the array is declared with a constant size, it it stack allocated? Would that break any existing code?

    • @lylobean
      @lylobean Před 10 měsíci +3

      Stack has a limited size.

    • @jackoberto01
      @jackoberto01 Před 10 měsíci +1

      You don't always want the array on the stack. If you have a field that exists throughout multiple methods heap allocation makes more sense. The stack should only be used for temporary variables

    • @lasselange1911
      @lasselange1911 Před 10 měsíci +1

      ​@@jackoberto01but shouldn't the compiler be able to see whether you are doing that? So if you are just using the array locally in that method, why not stack allocate it automatically?

  • @BlingPiece
    @BlingPiece Před 10 měsíci

    Have you switched to visual studio?

    • @BlingPiece
      @BlingPiece Před 10 měsíci +2

      Ignore me, you just mentioned why!

    • @amirhosseinahmadi3706
      @amirhosseinahmadi3706 Před 10 měsíci +3

      He demos the preview features in VS because they're only available in VS.

  • @Alguem387
    @Alguem387 Před 10 měsíci

    you can already do this with StructLayoutAttribute, tough i dont know if that worked with generics.
    I use StructLayoutAttribute it to map arbritary regions of a byte array coming from a UART interface into neatly meaningful structs

  • @Churdington
    @Churdington Před 10 měsíci +4

    We should consider that some of the new features for C# are in preparation for AI's impending widespread usage as a programming tool. Think about the new Interceptors. Those will allow AI to non-destructively create many experimental iterations of complete overhauls to existing systems without any hassle. AI can modify source code without having to modify source files, and if you don't like what the AI did, you just delete it, and instruct the AI to try again.
    Microsoft is currently one of the biggest investors in AI.

    • @saniel2748
      @saniel2748 Před 10 měsíci +2

      AI techbros just can't shut up

    • @saniel2748
      @saniel2748 Před 10 měsíci

      @@Churdington Problem is that you can never shut up and bring up AI every chance you get even if noone asked
      AI has high chance of either destrying society given to wrong people, or just killing people entirely. You're a lunatic if you're actually excited for this stuff

    • @Churdington
      @Churdington Před 10 měsíci

      @@saniel2748 Not sure that I understand what you mean. Your terminology of "AI Techbro" is obviously intended to be derogatory, but there doesn't seem to be a reason for it.
      AI is a practical tool that is currently seeing widespread use in the industry. I personally use it to improve my workflow, as do many other developers - both on personal and commercial projects. Generative AI for game development is already available through user made plugins, but official versions are coming. Unity's generative AI is currently in closed beta, and Epic Games is cooking something up for Unreal Engine.
      We haven't seen anything have this big of an impact on the industry in a very, very long time.

    • @saniel2748
      @saniel2748 Před 10 měsíci

      @@Churdington "Techbro" is a person detached from reality who saw new hype thing and thinks it'll now solve every problem ever so they can never shut up about it.
      You people are obnoxious, can't scroll internet for 5 seconds without another believer talks about WiDeSpreAD AI ADOPTION and FeaTuReS

  • @diadetediotedio6918
    @diadetediotedio6918 Před 10 měsíci +3

    Hmmm, it's an interesting concept, but don't you think it's just a wrapper around the pre-existing "fixed-size buffers" that already existed in C#?

    • @GumbootMan
      @GumbootMan Před 10 měsíci +2

      No because this new "inline array" feature is not as limited as the existing 'fixed' keyword. The existing C# fixed-size buffer feature only supported a limited subset of types; this new feature supports any type. Plus it doesn't require unsafe mode like it used to.

    • @diadetediotedio6918
      @diadetediotedio6918 Před 10 měsíci

      @@GumbootMan
      Hmmm, indeed, these are interesting points. But in that case wouldn't it make more sense to allow fixed to be used with all unmanaged types? I have a question too, you say it supports any type, does that mean it will also support managed objects?

  • @lolroflxd
    @lolroflxd Před 10 měsíci +1

    Actually I can use this in exactly one case :)

  • @dcuccia
    @dcuccia Před 10 měsíci +1

    Anyone care to speculate on why "they" need it? Will we see GPU implementations of this, for example? If that's the real reason "they" need it, then I'm glad they're building features for themselves! :)

  • @vitalyl1327
    @vitalyl1327 Před 10 měsíci

    How is it a niche use case? Stack-allocated arrays are essential for performance.

    • @nickchapsas
      @nickchapsas  Před 10 měsíci

      But performance is essential for a niche audience

    • @vitalyl1327
      @vitalyl1327 Před 10 měsíci

      @@nickchapsas this attitude is why all the modern software sucks so much... Performance is essential for the end users, first and foremost. Developers who find excuses like "whatever, I saved 10 minutes of my life writing crappier code, but the users can just upgrade their hardware to compensate" are the worst.

    • @vitalyl1327
      @vitalyl1327 Před 10 měsíci

      @@nickchapsas also, a lot of your videos are about performance, so you clearly care. Why do you think your audience does not?

  • @Dubzer
    @Dubzer Před 10 měsíci +2

    I like the idea, but I think it should be supported by the language. Like in rust you can use array type with fixed size [i32; 10]

  • @bluesillybeard
    @bluesillybeard Před 10 měsíci

    Having to make an entire struct just for a single array is a bit annoying to me, but I can think of a place in my project where this could be useful.

  • @KvapuJanjalia
    @KvapuJanjalia Před 6 měsíci

    This looks quite similar to what "fixed" keyword gets lowered to.

  • @ryanmusgrave6921
    @ryanmusgrave6921 Před 10 měsíci

    Can you do a video about copy and pasted code so I can get a buddy to shut up about "it's superiority" and show him why it is generally a bad idea?

  • @LeutnantJoker
    @LeutnantJoker Před 7 měsíci

    There is no difference between "features they need" and "features we need". We're all developers. Microsoft isn't occupied by magical elves. Every feature they need someone outside of Microsoft will be able to use for something cool. And at the endof the day, if Microsoft needs it, that means they want to improve something in .NET Core Libraries, which we all benefit from. So we may not 'need' it directly, but we always benefit from it. Either directly or because some third party library developer was able to use the feature for something cool.

  • @neociber24
    @neociber24 Před 10 měsíci +1

    The method is really weird, maybe they should reuse the fixed keyword for this

  • @mindstyler
    @mindstyler Před 10 měsíci

    Hey Nick, I've tried reaching you on twitter and email regarding some code, but am unsure if you received it. Anyway, great feature, definitely can already think of some use cases.

  • @XathaReiru
    @XathaReiru Před 10 měsíci

    I love the feature, but I dislike the syntax…

  • @roelbrook7559
    @roelbrook7559 Před 10 měsíci

    I don't quite agree with the "features they need, not what we need". The stuff Microsoft needs is the same stuff as (some of us) need. There's many more of "us" then there is of "them". I do like all the new features, but the implementation of these kinds of things are obscure. Unless you know about the specific feature, there's no way you could find it. Wouldn't this be simpler and more prominently implemented by just introducing a new type in System.Collections? Why does it need to be this way, with a struct and an attribute and a single field?

  • @lextr3110
    @lextr3110 Před 10 měsíci +7

    Becoming a Frankenstein language

  • @modernkennnern
    @modernkennnern Před 10 měsíci

    I would argue this is not really a "C# 12 feature", but more of a ".Net 8 feature"

  • @theMagos
    @theMagos Před 10 měsíci

    What's so "inline" about it? Adding code in another file is pretty anti-inline imo...

  • @cocoscacao6102
    @cocoscacao6102 Před 10 měsíci +5

    I understand why you need to put dumb thumbnails and clickbait your titles, but please consider putting somewhere what the actual topic is. I was searching through your old videos for some bits of info, and damn... It took me a lot to find it, because there's no term I can search for... Goddamn modern web and goldfish-brain people that are forcing content creators to resort to these tricks...

    • @nickchapsas
      @nickchapsas  Před 10 měsíci +6

      It's impossible to title videos liek this in a proper clickable way. If I just name the video "The new Inline Arrays coming in C# 12" then people won't actually click it because they will think it's just normal arrays. It's sad, I agree, but that's the state of CZcams. The topic is still in the description for SEO but the title has to be something clickable.

  • @hrchavz9694
    @hrchavz9694 Před 10 měsíci +1

    someone know some IA or program for change the voice of CZcams because I hate the voice of this guy

  • @TheOneAndOnlySecrest
    @TheOneAndOnlySecrest Před 10 měsíci +1

    I guess I have to move away from C# soon-ish. What MS does to this language is just aweful 😢
    Interceptors aka COMEFROM.
    Magic attributes to do stuff a source generator could also do.
    It is so sad to see my beloved language tortured like this...

    • @phizc
      @phizc Před 10 měsíci

      You would need an attribute to tell the source generator to implement it anyway.
      Sure, you could make a source generator that adds that private field, and mark the struct partial, but you're not really saving anything.

    • @TheOneAndOnlySecrest
      @TheOneAndOnlySecrest Před 10 měsíci +1

      @@phizc It would prevent obvious tech debt in the compiler.
      The SG can just be a throw away thing but CLR / Compiler stuff needs to be maintained for a long time as it would break existing code.
      Basically the current direction of C# is more like "Let's add this random workaround/hack" instead of taking a bit more time to "Fix it properly".
      All of this is caused by the extremly fast iteration of the language. There is just no time for a bigger feature to be implemented in less than half a year.

  • @numinaoneiron1655
    @numinaoneiron1655 Před 10 měsíci

    A similar approach to this can be found in System.Runtime.InteropServices.NativeMemory.