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

  Рет қаралды 32,381

Tarodev

Tarodev

Күн бұрын

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
@Tarodev 2 жыл бұрын
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
@syluxdev 2 жыл бұрын
Finally, I understood the principle of Stack and Heap, You Are A Legend
@WagnerGFX
@WagnerGFX 2 жыл бұрын
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.
@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!
@frankkubrick865
@frankkubrick865 2 жыл бұрын
You're great at making complicated concepts easy to understand, thank you!
@Tarodev
@Tarodev 2 жыл бұрын
You're welcome!
@Firebreak_2
@Firebreak_2 2 жыл бұрын
this is super useful. i've been using c# for over a year and never knew the difference. thanks a lot!
@jadonmullinex9389
@jadonmullinex9389 2 жыл бұрын
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 😊
@kawaiianthony8090
@kawaiianthony8090 2 жыл бұрын
Finally now i know what does the stack overflow error mean.
@Tarodev
@Tarodev 2 жыл бұрын
It all makes sense 😊
@cosmotect
@cosmotect 2 жыл бұрын
Covered so much stuff I needed to learn… awesome!
@abdrnasr
@abdrnasr 2 жыл бұрын
Very cool I was looking for this the other day. Glad you made a video about this topic.
@vietanhnguyen1415
@vietanhnguyen1415 Жыл бұрын
Man, you are a truly a savior to my C# Unity knowledge !!!
@Tarodev
@Tarodev Жыл бұрын
Happy to help 🙏
@dago6410
@dago6410 2 жыл бұрын
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.
@pixeldevlog
@pixeldevlog 2 жыл бұрын
Awesome video, Need more of this content !!!
@jumpkut
@jumpkut 2 жыл бұрын
Really good rundown! Love the stack/heap graphics. One day maybe I’ll understand it as well
@Destructivepurpose
@Destructivepurpose 2 жыл бұрын
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!
@victorlapin2080
@victorlapin2080 2 жыл бұрын
Great video 😊 I've totally enjoyed watching it
@sasquatchbgames
@sasquatchbgames 2 жыл бұрын
this...was REALLY well explained. Thanks so much for making all these videos!
@This-Was-Sparta
@This-Was-Sparta 2 жыл бұрын
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.
@ror123456789ify
@ror123456789ify 2 жыл бұрын
Awesome lecture!
@kyleme9697
@kyleme9697 2 жыл бұрын
Now I know what a stack overflow is. I feel like a computer engineer now !!
@doge9203
@doge9203 2 жыл бұрын
thanks I watched the whole thing but I want to hammer these topics into my head so ima come rewatch later on
@jbmgil
@jbmgil 4 ай бұрын
Your illustrations of the stack and heap allocations where didactically perfect!
@josephaltiok8414
@josephaltiok8414 2 жыл бұрын
This is extremely helpful thanks man. I never understood the difference before.
@danigarciafernandez8908
@danigarciafernandez8908 2 жыл бұрын
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!
@MrShark-qu5xx
@MrShark-qu5xx 2 жыл бұрын
This tied some of my disparate knowledge bits together, making me a better man
@rowdywabbid
@rowdywabbid 2 жыл бұрын
Great explanation and demo
@Frank_G_Finster
@Frank_G_Finster 2 жыл бұрын
Thank you for the helpful informations!
@ignisfatuus8844
@ignisfatuus8844 Жыл бұрын
Just a few days ago i found your videos and love your work ..... Plz don't stop
@maq3009
@maq3009 4 ай бұрын
I finally get stack and heap, thank you soooo much.
@mysterycube9891
@mysterycube9891 2 жыл бұрын
Super helpful thank you 💯💯💯
@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!
@Pasora
@Pasora 2 жыл бұрын
That was the best explanation I didn't know I needed THANK YOU.
@Tarodev
@Tarodev 2 жыл бұрын
You're welcome soso :)
@alexgeeves7096
@alexgeeves7096 Жыл бұрын
Amazing content man, please never stop, if I wasn't currently unemployed you would be my debut patreon subscription in a heartbeat.
@BillGeek
@BillGeek 2 жыл бұрын
Excellent video, somehow this all makes more sense when someone tells me about it instead of just reading about it.
@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
@cello91
@cello91 2 жыл бұрын
"Imagine a world where we couldn't compare strings with the equality operator" - welcome to java! 😂
@Nullscr1pt
@Nullscr1pt 2 жыл бұрын
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
@Un4GivNX
@Un4GivNX 2 жыл бұрын
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 :)
@danieletorrigiani
@danieletorrigiani 2 жыл бұрын
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.
@DevDunkStudio
@DevDunkStudio 2 жыл бұрын
Watched this 2 days ago and today I finally fixed a bug caused by interpreting this stuff wrong last week lol
@truth8483
@truth8483 Жыл бұрын
ROFL "better him than me, " i saw the little "fu" in there haha
@AlexBlackfrost
@AlexBlackfrost 2 жыл бұрын
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
@zekiozdemir420
@zekiozdemir420 2 жыл бұрын
Thank you
@alejandroherrera7582
@alejandroherrera7582 2 жыл бұрын
Great lesson, comment for algorithm
@mehmetakyuz5290
@mehmetakyuz5290 2 жыл бұрын
Much appreciate for the video! I wonder if there are good written detailed resources on these topics
@Andscool
@Andscool Жыл бұрын
VERY new dev here. Don’t understand shit but still very well made videos 👍
@anna_silver_moon
@anna_silver_moon 2 жыл бұрын
Quaternions!
@Tarodev
@Tarodev 2 жыл бұрын
Soooooooon
@cwdgamedev822
@cwdgamedev822 2 жыл бұрын
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'?
@CryShana
@CryShana 2 жыл бұрын
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! :)
@JulianRijken
@JulianRijken 2 жыл бұрын
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.
@jsn4591
@jsn4591 2 жыл бұрын
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 :)
@tommallama9663
@tommallama9663 2 жыл бұрын
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!
@vaibhavjaiswal799
@vaibhavjaiswal799 2 жыл бұрын
Talking about multi threading....do you have any future plans for Unity DOTS tutorial....?
@gregoryfenn1462
@gregoryfenn1462 2 жыл бұрын
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.
@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.
@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)
@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.
@Rovsau
@Rovsau 2 жыл бұрын
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.
@catpyjamas
@catpyjamas 2 жыл бұрын
Great video dude, subbed, even though you called me a nerd at the beginning.
@Tarodev
@Tarodev 2 жыл бұрын
Thanks nerd
@DevDunkStudio
@DevDunkStudio 2 жыл бұрын
Really informative! Thanks And didn't know about these strings :o
@Tarodev
@Tarodev 2 жыл бұрын
Tricky little buggers
@rediculai2584
@rediculai2584 4 ай бұрын
if anyone can answer what does he mean by the pointer for the struct at 10:16
@KLRGOFFIRE
@KLRGOFFIRE Жыл бұрын
Holy fuck this was an epiphany ... For so long I was wondering why certain variables became references, while others became copies. >.
@sajadtroll9186
@sajadtroll9186 2 жыл бұрын
i like your voice
@Tarodev
@Tarodev 2 жыл бұрын
Always hitting me with the compliments
@zohichnazirro8640
@zohichnazirro8640 2 жыл бұрын
Походу видео о кватернионах это аналог гайда на Брюмастера
@iiropeltonen
@iiropeltonen 2 жыл бұрын
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.
@CheeseChuckie
@CheeseChuckie 2 жыл бұрын
"Welcome back nerds" *clicks like*
@datablob
@datablob 2 жыл бұрын
I can feel the struct excitement coursing through my veins
@nirast2561
@nirast2561 2 жыл бұрын
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.
@r1pfake521
@r1pfake521 2 жыл бұрын
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.
@MandyLeeYT
@MandyLeeYT 2 жыл бұрын
🤓
@hermandarr6274
@hermandarr6274 2 жыл бұрын
funny looking python code.
@MaZyYTube
@MaZyYTube 2 жыл бұрын
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
@criadabatterista8647
@criadabatterista8647 2 жыл бұрын
So you are telling me stackoverflow isn't just a random name picked for a website.................?!?!?!?!?!
@Tarodev
@Tarodev 2 жыл бұрын
Crazy but true 😜
@swildermuth
@swildermuth 2 жыл бұрын
Love your content and style, but you need better lighting. (coming from another developer youtuber)
@RasistFrog
@RasistFrog 10 ай бұрын
Still waiting for the garbage collector video
@Tarodev
@Tarodev 10 ай бұрын
Stillwaitingskeleton.png
@jorhoto7064
@jorhoto7064 2 жыл бұрын
int one = 12; I think this line breaks the immersion
@Tarodev
@Tarodev 2 жыл бұрын
It is a bit silly
@urlloader8372
@urlloader8372 2 жыл бұрын
"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!
@Betruet
@Betruet 2 жыл бұрын
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
@restushlogic5794
@restushlogic5794 2 жыл бұрын
I thought struct is faster than class for entire time.
@serveladik
@serveladik 2 жыл бұрын
Kinda hard code to undetstand Need some exmpls from the typical game dev solutions
@alittlelightcse2762
@alittlelightcse2762 2 жыл бұрын
Data is stored in the balls.
@Tarodev
@Tarodev 2 жыл бұрын
lol
@yusufulutas
@yusufulutas 10 ай бұрын
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?
C# IEnumerable & IEnumerator
25:15
Tarodev
Рет қаралды 33 М.
How I prepare to meet the brothers Mbappé.. 🙈 @KylianMbappe
00:17
Celine Dept
Рет қаралды 55 МЛН
Did you find it?! 🤔✨✍️ #funnyart
00:11
Artistomg
Рет қаралды 123 МЛН
Eccentric clown jack #short #angel #clown
00:33
Super Beauty team
Рет қаралды 24 МЛН
C# Value Types and Reference Types
32:49
Coding Tutorials
Рет қаралды 4,6 М.
Stack vs Heap Memory - Simple Explanation
5:28
Alex Hyett
Рет қаралды 185 М.
Where are types allocated in .NET and why people get it so wrong
14:35
C# Nullable reference types - No more null reference exceptions!
18:06
.Net Memory Allocations and Performance
52:28
Shiv Kumar
Рет қаралды 31 М.
C#: The Heap and the Stack
9:50
Edward Tanguay
Рет қаралды 35 М.
LEARN how to pass VALUE TYPES  by REFERENCE in C# - Ref, In and Out
24:45
tutorialsEU - C#
Рет қаралды 3,5 М.
Unity Code Optimization - Do you know them all?
15:49
Tarodev
Рет қаралды 181 М.
C# Value vs Reference Types Explained
6:40
Mark Inman
Рет қаралды 1,1 М.