C# Tutorial - Using Structs

Поделиться
HTML-код
  • Опубликовано: 13 сен 2024

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

  • @ahmadyazdany2102
    @ahmadyazdany2102 2 года назад +1

    I saw multiple videos about this topic and none of them has been more easy to undrestand than this one . Thanks

  • @75STARFISH
    @75STARFISH 2 года назад +1

    Wow myguy. A lot of bigman keywords. I get the jist of what a struct is. Thanks for the video! I'll sub

    • @nickproudprogrammer
      @nickproudprogrammer  2 года назад

      Thanks! Glad it was useful and grateful for the sub. Let me know if you would like to say any other specific topics covered.

  • @krs-tube
    @krs-tube 2 года назад

    You said there's a restriction for structs to be initialized via constructor, why would you give myString {set;} ?

  • @KoziLord
    @KoziLord 2 года назад

    Structs are not allocated on the stack, they're allocated inline, compared to classes which store a pointer inline that points to the actual data somewhere on the managed heap. What does that mean in practice?
    Locals are always stack allocated*, the difference is that the class has that layer of indirection I just mentioned. If you have a local null reference type, you have a stack allocated pointer but no heap allocation happens (the object doesn't exist, it's null).
    However, an array is a ref type, if you allocate an array of structs all those structs are heap allocated contiguously.
    An array of ref types is a heap allocated contiguous array of pointers to objects scattered all around the memory.
    The additional pointer dereference is not the issue, a memory load will have to happen for many cases anyway, the issue is what memory you're loading. It's not the stack vs the heap that affects the speed of the memory load, it's the memory access patterns that matter.
    Accessing the same region of memory as well as accessing the memory in predictable linear patterns (say, iterating an array) is fast thanks to CPU caches and CPU prefetching (This ( ruclips.net/video/WDIkqP4JbkE/видео.html ) talk from Scott Myers is a great introduction to the topic).
    Value types also don't store any additional data with them unlike managed objects which store the object header (a pointer worth of data and a virtual table pointer used for virtual dispatch, which also serves as a type ID), which means that a conversion from MyStruct to MyInterface has to box (heap allocate an object and copy your struct's data to that object), otherwise it'd have no way of looking up the type to call whatever interface method you're trying to call.
    The main reason to use interfaces with structs is generics, where the code gets specialised for each type passed as a generic argument, meaning no boxing happens and you're not paying any performance penalty for stuff like interface calls.
    (*There are exceptions related to stuff like yield statements which turn into state machines that are heap allocated)