Value & Reference types in C#. Write Better Code!

Value vs reference types. Stack vs heap. These are fundamental concepts to understand if you wish to write performant code. Learn the characteristics of value and reference types and how they're allocated to memory. Learn how StackOverflowException occurs and how to fix and prevent them.
❤️ Become a Tarobro on Patreon: / tarodev
=========
🔔 SUBSCRIBE: bit.ly/3eqG1Z6
🗨️ DISCORD: / discord
✅ MORE TUTORIALS: / tarodev
0:00 - whatever, intro I guess
0:37 - value types / structs
2:00 - reference type / class
3:00 - stack & heap
3:27 - stack example
5:57 - heap example
8:47 - when to use one over the other
11:30 fix StackOverflowException
13:15 - Bonus: strings

Пікірлер: 179

  • @Tarodev
    @Tarodev2 жыл бұрын

    Damn, I miss spoke a few times in this recording so there are a few annotations! Don't shoot me guys Also, explode this thread

  • @jdnots143

    @jdnots143

    2 жыл бұрын

    represent

  • @gralcio

    @gralcio

    2 жыл бұрын

    misbrained

  • @jerem3135

    @jerem3135

    2 жыл бұрын

    👍

  • @DalamarTD7

    @DalamarTD7

    2 жыл бұрын

    Boom!

  • @Reafuse111

    @Reafuse111

    2 жыл бұрын

    waku waku

  • @syluxdev
    @syluxdev2 жыл бұрын

    Finally, I understood the principle of Stack and Heap, You Are A Legend

  • @JW-uu9je
    @JW-uu9je Жыл бұрын

    I was not ready for this video 1 year ago! Came back today and I think I understand my games poorer performance issues better...I likely still need to watch this video like 5 more times XD

  • @Tarodev

    @Tarodev

    Жыл бұрын

    So good coming back and realizing you've grown as a developer. Well done!

  • @Firebreak_2
    @Firebreak_22 жыл бұрын

    this is super useful. i've been using c# for over a year and never knew the difference. thanks a lot!

  • @WagnerGFX
    @WagnerGFX2 жыл бұрын

    One rule I usually follow is to use structs to store data that is short lived and either read-only or independent of other copies. Some good examples are event arguments, their main function is to return data to multiple places and be deallocated right after. If you are making a game with many events firing every frame, classes will just overwork the GC, but with a struct there won't be any GC and the stack allocation is minimal.

  • @abdrnasr
    @abdrnasr2 жыл бұрын

    Very cool I was looking for this the other day. Glad you made a video about this topic.

  • @cosmotect
    @cosmotect2 жыл бұрын

    Covered so much stuff I needed to learn… awesome!

  • @Destructivepurpose
    @Destructivepurpose2 жыл бұрын

    Awesome video man! I've always been a little unsure of the differences between the two and when to use structs vs classes but you explained it in a way that made complete sense. The animated diagrams you showed of the Stack and Heap were so useful!

  • @frankkubrick865
    @frankkubrick8652 жыл бұрын

    You're great at making complicated concepts easy to understand, thank you!

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    You're welcome!

  • @This-Was-Sparta
    @This-Was-Sparta2 жыл бұрын

    This answered a few questions I didn't even know I had, thanks Taro! Definitely going to have to watch this a couple times over to really absorb all the info, lol.

  • @sasquatchbgames
    @sasquatchbgames2 жыл бұрын

    this...was REALLY well explained. Thanks so much for making all these videos!

  • @jumpkut
    @jumpkut2 жыл бұрын

    Really good rundown! Love the stack/heap graphics. One day maybe I’ll understand it as well

  • @danigarciafernandez8908
    @danigarciafernandez89082 жыл бұрын

    Super, super, super interesting video. Great work! I´ve been following you for a while and with every new video I´ve improved as a dev. Thanks, keep up the good work!

  • @kyleme9697
    @kyleme96972 жыл бұрын

    Now I know what a stack overflow is. I feel like a computer engineer now !!

  • @josephaltiok8414
    @josephaltiok84142 жыл бұрын

    This is extremely helpful thanks man. I never understood the difference before.

  • @kawaiianthony8090
    @kawaiianthony80902 жыл бұрын

    Finally now i know what does the stack overflow error mean.

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    It all makes sense 😊

  • @pixeldevlog
    @pixeldevlog2 жыл бұрын

    Awesome video, Need more of this content !!!

  • @MrShark-qu5xx
    @MrShark-qu5xx2 жыл бұрын

    This tied some of my disparate knowledge bits together, making me a better man

  • @overrideFunction
    @overrideFunction Жыл бұрын

    Fantastic explanation. I learned a lot. Sounds like if your initializing a variable with new it's going on the heap. I never understood why some needed this and some did not now its perfectly clear!

  • @ignisfatuus8844
    @ignisfatuus8844 Жыл бұрын

    Just a few days ago i found your videos and love your work ..... Plz don't stop

  • @Pasora
    @Pasora2 жыл бұрын

    That was the best explanation I didn't know I needed THANK YOU.

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    You're welcome soso :)

  • @BillGeek
    @BillGeek2 жыл бұрын

    Excellent video, somehow this all makes more sense when someone tells me about it instead of just reading about it.

  • @victorlapin2080
    @victorlapin20802 жыл бұрын

    Great video 😊 I've totally enjoyed watching it

  • @alexgeeves7096
    @alexgeeves7096 Жыл бұрын

    Amazing content man, please never stop, if I wasn't currently unemployed you would be my debut patreon subscription in a heartbeat.

  • @jbmgil
    @jbmgil4 ай бұрын

    Your illustrations of the stack and heap allocations where didactically perfect!

  • @maq3009
    @maq30094 ай бұрын

    I finally get stack and heap, thank you soooo much.

  • @steveradtke1308
    @steveradtke1308 Жыл бұрын

    Wow you put a lot of effort into this video. And I understood it. Ngl I watched thr first 2 mins and I was lost, but as I continued watching it all made sense! Thanks

  • @dago6410
    @dago64102 жыл бұрын

    Been coding in unity for like 5 years now. THis is still not just beyond the scope of what my brain can access, but im afraid it will forever be.

  • @ror123456789ify
    @ror123456789ify2 жыл бұрын

    Awesome lecture!

  • @vietanhnguyen1415
    @vietanhnguyen1415 Жыл бұрын

    Man, you are a truly a savior to my C# Unity knowledge !!!

  • @Tarodev

    @Tarodev

    Жыл бұрын

    Happy to help 🙏

  • @Frank_G_Finster
    @Frank_G_Finster2 жыл бұрын

    Thank you for the helpful informations!

  • @jadonmullinex9389
    @jadonmullinex93892 жыл бұрын

    The visuals looked like they took a lot of work to create, but they really helped me understand what's happening under the hood. Thank you!

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    That makes it worth the effort 😊

  • @doge9203
    @doge92032 жыл бұрын

    thanks I watched the whole thing but I want to hammer these topics into my head so ima come rewatch later on

  • @rowdywabbid
    @rowdywabbid2 жыл бұрын

    Great explanation and demo

  • @danieletorrigiani
    @danieletorrigiani2 жыл бұрын

    Great video. There is a lot of advice out there regarding the dangers of heap allocation and garbage collection, so it's good to see one that covers the "other side" of the balance.

  • @mysterycube9891
    @mysterycube98912 жыл бұрын

    Super helpful thank you 💯💯💯

  • @AlexBlackfrost
    @AlexBlackfrost2 жыл бұрын

    Great video! Understanding the difference between values and references was the topic that took me the longest to learn when I was learning how to program

  • @Un4GivNX
    @Un4GivNX2 жыл бұрын

    Good entry video. The next one should go deeper and explore passing structs by ref for even better perfs.

  • @Miguel7456lmkuutti
    @Miguel7456lmkuutti Жыл бұрын

    Nice to have finally found a channel that gets down to the nitty griddy of coding! Most of these tutorial channels are honestly just pointing out fairly obvious things u can find out on your own... And the big problem with unity related forum searches is, that most of the users are entry level devs and don't understand longevity, or even the questions being asked. Hopefully your content will provide some much needed substance to this void of information! (Ok, that sounded pretty harsh on the other channels, but appreciate the 'deep dive' aspect!)

  • @Tarodev

    @Tarodev

    Жыл бұрын

    Glad I could provide some lower level content for you :)

  • @DevDunkStudio
    @DevDunkStudio2 жыл бұрын

    Watched this 2 days ago and today I finally fixed a bug caused by interpreting this stuff wrong last week lol

  • @cello91
    @cello912 жыл бұрын

    "Imagine a world where we couldn't compare strings with the equality operator" - welcome to java! 😂

  • @Nullscr1pt
    @Nullscr1pt2 жыл бұрын

    What’s more impressive? The c# or the after effects work making the c# understandable. Both are! Thanks brother.

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Took me ages my man. I need to skill up on my editing

  • @mehmetakyuz5290
    @mehmetakyuz52902 жыл бұрын

    Much appreciate for the video! I wonder if there are good written detailed resources on these topics

  • @truth8483
    @truth84832 жыл бұрын

    ROFL "better him than me, " i saw the little "fu" in there haha

  • @alejandroherrera7582
    @alejandroherrera75822 жыл бұрын

    Great lesson, comment for algorithm

  • @zekiozdemir420
    @zekiozdemir4202 жыл бұрын

    Thank you

  • @tommallama9663
    @tommallama96632 жыл бұрын

    What a gorgeous way to explain the differences between Value and Reference Types, while still being able to explain the Stack and Heap. Thank you so so much for this!

  • @Andscool
    @Andscool2 жыл бұрын

    VERY new dev here. Don’t understand shit but still very well made videos 👍

  • @anna_silver_moon
    @anna_silver_moon2 жыл бұрын

    Quaternions!

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Soooooooon

  • @CryShana
    @CryShana2 жыл бұрын

    Very nice video and really beautifully explained. For people interested, I want to mention if you want to make sure that a struct does not escape to the heap via collections, boxing or whatever ... you can use the "ref" keyword and create a struct like "ref struct StructName {}", this will make sure you are not doing anything on the heap by accident. ref structs can also contain Span fields, which can be useful.

  • @Jicefrost
    @Jicefrost Жыл бұрын

    64 bit comment - nice video! :)

  • @cwdgamedev822
    @cwdgamedev8222 жыл бұрын

    Great tutorial, thank you very much! Question: what happens if an element buried deep in the stack is ready to be deallocated? Like at 4:56, what if 'one' should be deallocated before 'two' and 'three'?

  • @jsn4591
    @jsn45912 жыл бұрын

    Thanks for elevating us man! I've learned so much from you and I love being able to pop back in for a refresher when necessary. You mention the 1MB Stack limit, I'm guessing there are few situations where we need to be weary of this, is there a heap limit too? (is that our available RAM?)

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    That's right, but it's quite limited on 32 bit systems. The program is allocated a certain amount and can continue to request more as required. Glad you enjoyed the video :)

  • @JulianRijken
    @JulianRijken2 жыл бұрын

    Welcome back nerds... The what did you just call me!

  • @pj-wille

    @pj-wille

    2 жыл бұрын

    My boy you clicked on a video called "Value & Reference types in C#. Write Better Code!" you have no defense! Neither do I!

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    @@pj-wille You nerds

  • @JulianRijken

    @JulianRijken

    2 жыл бұрын

    @@pj-wille Dammit, fair enough.

  • @millerbyte5579
    @millerbyte5579 Жыл бұрын

    Do you have any sort of FAQ talking about the tools you use to edit and produce these videos? Because as the kids say; this fire be bussin', knaw mean, no buggin'.

  • @Tarodev

    @Tarodev

    Жыл бұрын

    I use premiere and after effects my man. I'm glad the visuals added to the experience as I remember them taking quite a long time.

  • @catpyjamas
    @catpyjamas2 жыл бұрын

    Great video dude, subbed, even though you called me a nerd at the beginning.

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Thanks nerd

  • @DevDunkStudio
    @DevDunkStudio2 жыл бұрын

    Really informative! Thanks And didn't know about these strings :o

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Tricky little buggers

  • @vaibhavjaiswal799
    @vaibhavjaiswal7992 жыл бұрын

    Talking about multi threading....do you have any future plans for Unity DOTS tutorial....?

  • @Rovsau
    @Rovsau2 жыл бұрын

    Perhaps this was mentioned, but since Classes aren't copied the way structs are, note that one can copy a class by passing the object into the class constructor. var copy = new MyClass(original);

  • @MulleDK19

    @MulleDK19

    2 жыл бұрын

    No? Not unless the class specifically has support for that.

  • @Rovsau

    @Rovsau

    2 жыл бұрын

    @@MulleDK19 Meaning any class with a constructor. There is no extra code.

  • @gregoryfenn1462
    @gregoryfenn14622 жыл бұрын

    Is there a way to use the address of a struct to pass it by reference, to avoid the 1000x stack memory problem in your recursive example? 90% of my coding experience is in C where everything is a value type, basic numeric types or structs thereof, so I must admit that I’m more comfortable using structs over classes wherever possible.

  • @NewEnglandModz
    @NewEnglandModz Жыл бұрын

    So would it be redundant to do... Foo(ref MyClass class) ...since classes are already referenced? Or does it create a duplicate if it enters a method if it was done normally, like this... Foo(MyClass class)

  • @KLRGOFFIRE
    @KLRGOFFIRE Жыл бұрын

    Holy fuck this was an epiphany ... For so long I was wondering why certain variables became references, while others became copies. >.

  • @sajadtroll9186
    @sajadtroll91862 жыл бұрын

    i like your voice

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Always hitting me with the compliments

  • @MandyLeeYT
    @MandyLeeYT2 жыл бұрын

    🤓

  • @MrKetrab1984
    @MrKetrab1984 Жыл бұрын

    What happens to prefab, suppose we have a prefab list, they all go into memory? , I assume they are only on the list, not instansiet on scene.

  • @rediculai2584
    @rediculai25844 ай бұрын

    if anyone can answer what does he mean by the pointer for the struct at 10:16

  • @zohichnazirro8640
    @zohichnazirro86402 жыл бұрын

    Походу видео о кватернионах это аналог гайда на Брюмастера

  • @CheeseChuckie
    @CheeseChuckie2 жыл бұрын

    "Welcome back nerds" *clicks like*

  • @datablob
    @datablob2 жыл бұрын

    I can feel the struct excitement coursing through my veins

  • @MaZyYTube
    @MaZyYTube2 жыл бұрын

    Good to know. I am working on my own networking stuff. I was really focused on doing automated serialization, rpcs, networkvariable etc. This helps to understand and to be careful. But even I have over 10 years C#.. I never thought about it the values in side Coords. I really couldn't say if both coordswill have same values if you change it. Or I had blackout :D You should also mention ref keyword. I think it is also very important to know

  • @r1pfake521
    @r1pfake5212 жыл бұрын

    Kinda off topic but it always annoyed me that there is no mutable string version in C#. Game UI is very dynamic, so even if you want to do a simple thing like a tooltip for a status effect with a duration timer you have to allocate a whole new string after the timer ticks (so for example every second) to update the text. Sure there are things like StringBuilder etc but in the end the ToString call will still allocate a new string instance. The only way to avoid this is to use unsafe code and preallocate a large "buffer" string to modify the char values with pointers, but this can lead to other issues.

  • @swildermuth
    @swildermuth2 жыл бұрын

    Love your content and style, but you need better lighting. (coming from another developer youtuber)

  • @criadabatterista8647
    @criadabatterista86472 жыл бұрын

    So you are telling me stackoverflow isn't just a random name picked for a website.................?!?!?!?!?!

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Crazy but true 😜

  • @nirast2561
    @nirast25612 жыл бұрын

    I remember I had an issue a while ago where I wrote something like obj1 = obj2, and I couldn't figure out why modifying obj2 would also affect obj1. I eventually realized it was because of references, which I didn't know that's how classes worked in C#. It tripped me up because I was used to C++'s use of the & symbol to denote reference. Also didn't know that structs are value types, that should come in handy. Does any other language do that where structs are value and classes are reference? As far as I can tell, C++ and Java just differentiate on the default visibility.

  • @hermandarr6274
    @hermandarr62742 жыл бұрын

    funny looking python code.

  • @iiropeltonen
    @iiropeltonen2 жыл бұрын

    So on Unity New vector3 always causes ja heap allocation? Should we avoid using it in Update and Coroutines? Instead use a member variable and modify it recursively?

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    Unitys Vector3 is also a struct, so no heap allocation there. It's perfectly fine to use in update.

  • @jorhoto7064
    @jorhoto70642 жыл бұрын

    int one = 12; I think this line breaks the immersion

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    It is a bit silly

  • @RasistFrog
    @RasistFrog10 ай бұрын

    Still waiting for the garbage collector video

  • @Tarodev

    @Tarodev

    10 ай бұрын

    Stillwaitingskeleton.png

  • @urlloader8372
    @urlloader83722 жыл бұрын

    "Imagine a world where we couldn't compare strings with the equality operator (s1 == s2). Chaos!" LMAO! Are you taking a jab at Java? 🤭🤭 #tarodevvsjava. Awesome video man!

  • @restushlogic5794
    @restushlogic57942 жыл бұрын

    I thought struct is faster than class for entire time.

  • @serveladik
    @serveladik2 жыл бұрын

    Kinda hard code to undetstand Need some exmpls from the typical game dev solutions

  • @Betruet
    @Betruet2 жыл бұрын

    Yo... you cut your hair. I thought you would go wild man. A bit disappointing. Video is quality tho 😄

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    I didn't! Don't worry, it'll grow faaaaaaast

  • @Betruet

    @Betruet

    2 жыл бұрын

    @@Tarodev oh good! and yeah I learned a tonne here so tyvm

  • @alittlelightcse2762
    @alittlelightcse27622 жыл бұрын

    Data is stored in the balls.

  • @Tarodev

    @Tarodev

    2 жыл бұрын

    lol

  • @yusufulutas
    @yusufulutas10 ай бұрын

    I'm sorry but even what you say about stack and heap generally correct, for csharp it's wrong. All class variables(class field w/e) are stored in the heap not in the stack. In C/C++ you can create a variable without a class so you can keep a variable in the stack but in csharp everything is created in class (could be changed in new implementations Idk). The value of a variable of reference type is a reference to heap memory. So basically , if a variable is not a local variable (created in a function) it's always in the heap. Again this is for csharp not for general.

  • @Tarodev

    @Tarodev

    10 ай бұрын

    That's exactly what I said though? 🤔

  • @yusufulutas

    @yusufulutas

    10 ай бұрын

    @@Tarodev You did create some variables outside of a function and and said these are in stack? Sorry m aybe I misunderstood?