How To Use Recursion in C#

  Рет қаралды 9,290

IAmTimCorey

IAmTimCorey

Күн бұрын

Пікірлер: 66
@technovikingnik
@technovikingnik 2 ай бұрын
In my humble opinion directory tree example is much more reality alike than some abstract "fibonacci sequence", more complex alternative is searching/traversing binary trees.. Well done sir.
@troymitchel4790
@troymitchel4790 2 ай бұрын
Exactly. In the past I had to use this with Active Directory. Also use this with Feature Trees in SolidWorks custom apps.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Thank you!
@animeboy93
@animeboy93 3 күн бұрын
@@troymitchel4790 I've had to use recursion to detect if certain controls were containers and dive into them to format controls or find other controls.
@aleksejspiscevs
@aleksejspiscevs 2 ай бұрын
I would like to have the ability to talk for 20 minutes about the recursion.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Now you have a model. There’s actually a lot more to cover, so you could probably go for 45 minutes if you knew the topic well.
@darylbeaumont8855
@darylbeaumont8855 2 ай бұрын
'To understand recursion, you must first understand recursion.' Joking aside, nice video and +1 for not using a math example!
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Thanks!
@F4ir8or
@F4ir8or 2 ай бұрын
Ahhh recursion, always fun. I still remember the first time I had to use recursion - it broke my brain 😅 Great video! Good example that is easy to follow and explained nicely 👍
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Thank you!
@Ragnovlod
@Ragnovlod 2 ай бұрын
Cool. Just yesterday I worked around a situation that could otherwise have been handled by this. Thanks Tim!
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
You are welcome.
@studentsheaven-d8v
@studentsheaven-d8v 2 ай бұрын
Lovely, looking forward to more such videos. A playlist of top interview questions solutions and walkthroughs will be heaven for us if possible of course dear Tim.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
I'm considering it.
@rufarokatsamba2093
@rufarokatsamba2093 Ай бұрын
Thanks Tim, the example used is more relatable
@IAmTimCorey
@IAmTimCorey Ай бұрын
I’m glad.
@coujean99
@coujean99 2 ай бұрын
Changing (depth > 0) for (depth != 0) would easily allow you to set a limited or unlimited amount of depth using -1 😊 Good example!
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
The problem with that is that if you skip over 0, then you will have an infinite depth when you don't expect it.
@coujean99
@coujean99 2 ай бұрын
⁠​⁠@@IAmTimCoreyThanks for your answer, master! I think that I'm missing something in your explanation. If I set a maximum of 4 depth, then it will stop at 0, but if I set -1 meaning infinite, well it will go forever until the end of the depth, no? 🤔
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
In a perfect world, yes. However, the reason for loops use less than for their check is in case you accidentally skip a number. So in your example, let's say you had a bug in your code where you modified the number twice instead of one time. In that case, it would be 4, 2, 0. Perfect. That works. Ship it to production. Now imagine you get into production, but you are asking for three levels deep instead of four. Now it would be 3, 1, -1, -3, etc. forever. A not equals only checks for one specific exit case. A less than checks for that specific exit case, plus a range of accidental exit cases as well. It isn't perfect, but it is an added protection.
@coujean99
@coujean99 2 ай бұрын
@@IAmTimCorey Ok, I understand. Thank you for your precisions!
@Zakaria_TheWolf
@Zakaria_TheWolf 2 ай бұрын
Amazing Lesson ✅
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Thanks!
@kilworthman
@kilworthman 2 ай бұрын
Oh the towers of hanoi from my C÷÷ days comes flodding back !! Might try and revisit that for the fun just to see if it makes more or less sense 20 yrs later !!
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Sounds good.
@kumar315
@kumar315 2 ай бұрын
Great video, thanks...can you please do a video on yield return keyword
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Done: kzbin.info/www/bejne/d3LdaaRsmbR2j80si=2YfMEdeIwp7TFrFw
@kumar315
@kumar315 2 ай бұрын
@@IAmTimCorey thankyou, you are awesome 😎
@ademineshat
@ademineshat 2 ай бұрын
Great. Thanks 👍
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
You are welcome.
@melk48111
@melk48111 2 ай бұрын
nicely explained.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Thank you!
@MartinKramer-ff5mt
@MartinKramer-ff5mt 2 ай бұрын
I often prefer the stack based "recursion", and have it all in the same method namespace RecursionStack; internal class Program { static void Main(string[] args) { Stack stack = new Stack(); stack.Push(@"D:\temp"); string actDir; while (stack.Count > 0) { actDir = stack.Pop(); Console.WriteLine(actDir); foreach (var item in Directory.GetDirectories(actDir)) stack.Push(item); } } }
@conradjacobs3018
@conradjacobs3018 2 ай бұрын
In order to understand recursion you have to understand recursion…
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
That’s why you should understand recursion.
@conradjacobs3018
@conradjacobs3018 2 ай бұрын
@@IAmTimCorey but to understand recursion…
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
I've got a video that could help you understand it better: kzbin.info/www/bejne/nHTSgoNtm6ukpdksi=9ELP8l-shAzd82sM
@oliverjohnson2160
@oliverjohnson2160 2 ай бұрын
Instead of depth could we have used say directories with files only as the base case for the recursion example ?
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
We did use that when we didn’t specify a depth. When the folder has no subfolders, it stops.
@holger_p
@holger_p 2 ай бұрын
That's more the minimum basic about recursions, nothing about endless recursion, stack overflow, etc.. In this sample, the finitness is external given, by the file system.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Nothing about endless recursion or stack overflows? Did you watch the second half of the video? I covered that quite a bit. I didn’t demonstrate creating that type of issue, but I covered preventing it.
@holger_p
@holger_p 2 ай бұрын
@@IAmTimCorey Well, it's essentially necessary, to think about the end of recursion. You presented it as kind of optional to increase comfort. However, I would just encourage you to mark videos as for "bloody beginners" or as "Advanced Topics/News/Upgrades" or so. To find out "Do I already know it" I have no other chance, when to watch the video. If there is 5% new to me, it is worth it. Between "Blazor permanent storage" finding a video "what is a for-loop", or here "what is recursion"; it's kind of mutual exclusive audience.
@studentsheaven-d8v
@studentsheaven-d8v 2 ай бұрын
something new, will continue the C# start to finish from tomorrow.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Great!
@_samirdahal
@_samirdahal 2 ай бұрын
Me trying to solve this with carry/borrow method: 18 - 9 _____ 8 carries 1 so it becomes 18 So I do 18 - 9 _____ 8 carries 1 so it becomes 18 So I do 18 - 9 _____ 8 carries 1 so it becomes 18 So I do 18 - 9 _____ StackOverflowException
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
That's what I talked about in the video - make sure you have a floor or a depth limit. In this case, you've made an error in your formula that would create an infinite loop. This would be true if you used a for loop or a while loop as well.
@codyjmathis
@codyjmathis Ай бұрын
I have to recursively watch this video to understand.
@IAmTimCorey
@IAmTimCorey Ай бұрын
I wouldn't say that, but this video does have a prerequisite: kzbin.info/www/bejne/nHTSgoNtm6ukpdksi=rSqQxnh3wqIlwuKE
@K03N88
@K03N88 2 ай бұрын
How come you have no code for the program itself at the top? I would expect something like: namespace RecursionDemo { internal class Program { static void Main(string[] args)
@TheCorruptedClan
@TheCorruptedClan 2 ай бұрын
In newer versions of .net this structure is implied in program.cs. I think the option is at project setup called Top level statements
@_samirdahal
@_samirdahal 2 ай бұрын
Just need to Uncheck "Do not use Top-level Statements" during project setup.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
In .NET 6, the startup of projects was greatly streamlined. I did a video on what this change is and why it was a good thing: kzbin.info/www/bejne/l4SxoqSQpr6HoZYsi=blmTDzn6b1-V50ZZ
@K03N88
@K03N88 2 ай бұрын
@@IAmTimCorey Ah.. I'm using mainly 4.8 for add-ins to connect with a program specific API. Later is not supported.
@smeaden8947
@smeaden8947 2 ай бұрын
Please don't do this.
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
Why? Recursion is an important part of software development.
@ace90210ace
@ace90210ace 2 ай бұрын
Yeah this example is a fundamental and perfect example where recursion is the best place to start. If you start listing files in directories iteratively without a very good reason you are making things way harder and more complex for no reason.
@holger_p
@holger_p 2 ай бұрын
Soften it to: Do it with care, and if possible, avoid it. Like computing the faculty x! of something f(long x) => (x==0) ? 1 : f(x-1)*x; would perfectly work, but a simple for loop is faster and safer. The recursive implementation would even crash on f(40000) and there is no chance to forecast, when the exact crash will happen. (Stack size is limited to 4MB and here we are putting 40.000*8 bytes on the stack.)
@timyoung6495
@timyoung6495 2 ай бұрын
My takeaway from this video was: recursion is another tool in your development toolbox, here is how you can use it and, when you use it, here are pitfalls you need to consider. I did not see anything in the video that said recursion should always be used (where there are better options to get the same task done). Even if you think it should not be used, you are not always in control of the code you inherit, so I knowing how a particular feature is used is still useful because you may inherit code which you need to support. I used recursion a lot for tracing precedents and dependents in Excel formulas for forensic auditing, for instance.
@oragnerby
@oragnerby 2 ай бұрын
First
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
👍🏻
@pl4gueis
@pl4gueis 2 ай бұрын
Nice video but even with a proper base case you can run into the stackoverflow because C# is a terrible language for recursion. Its better to use Linq or while loops instead because C# lacks tail call optimization. F# does have it though.
@keyser456
@keyser456 2 ай бұрын
There are plenty of methods you can use in C# to prevent stack overflows and that includes recursion. lol @ F#
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
It isn’t a terrible language for recursion. You can absolutely use recursion safely in C#. It is more a matter of how the languages are designed and what is the preference. There is a reason why C# doesn’t have TCO. It wouldn’t provide the value that it does to F#. That’s a design choice. blog.objektkultur.de/about-tail-recursion-in-.net/
@pl4gueis
@pl4gueis 2 ай бұрын
@@IAmTimCorey Quote from your link: "as a more imperative language, iterative loops are conceptionally fine and (optimizing) deep recursion makes debugging harder as stack traces are destroyed. Thus, C# wants you to write loops instead and the compiler never wants TCO to happen." So as I originally said. Recursion in C# is possible but loops are favoured. The argument about preserving stack traces in C# makes sense but the critique stands C# is terrible for recursion and neither you nor @keyser456 mentioned any way to prevent stack overflows. If its possible that would be great but that information isn't shared. Creating a potential timebomb with recursion in C# is just terrible code. Sure today it works but it could very well lead to stack overflow at some point if for example the folder structure that gets processed increases by a lot. Edit: Even the depth like its implemented in the video does not prevent it. The caller could simply pass a huge number as depth because he wants to do something with all the folders and runs into stack overflow.
@ousmanetall1286
@ousmanetall1286 2 ай бұрын
Second
@IAmTimCorey
@IAmTimCorey 2 ай бұрын
👍🏻
How IDisposable and Using Statements Work Together in C#
10:01
IAmTimCorey
Рет қаралды 32 М.
My MEAN sister annoys me! 😡 Use this gadget #hack
00:24
PRANK😂 rate Mark’s kick 1-10 🤕
00:14
Diana Belitskay
Рет қаралды 8 МЛН
Disrespect or Respect 💔❤️
00:27
Thiago Productions
Рет қаралды 36 МЛН
小路飞还不知道他把路飞给擦没有了 #路飞#海贼王
00:32
路飞与唐舞桐
Рет қаралды 76 МЛН
Is Functional Programming DEAD Already?
21:07
Continuous Delivery
Рет қаралды 53 М.
C# LinkedList Tutorial How to Use A Linked List
17:00
Journey To Programming
Рет қаралды 50 М.
208. Separating AI Hype from AI Reality
19:49
IAmTimCorey
Рет қаралды 10 М.
Tail Recursion Explained - Computerphile
16:05
Computerphile
Рет қаралды 174 М.
Why Didn't He Get the Job? Let's Find Out! // Code Review
27:25
The Cherno
Рет қаралды 144 М.
Advanced Breakpoints and Tracepoints in C#
22:36
IAmTimCorey
Рет қаралды 6 М.
The New Option and Result Types of C#
15:05
Nick Chapsas
Рет қаралды 77 М.
How To Create Generics in C#, Including New Features
38:51
IAmTimCorey
Рет қаралды 50 М.
Why 4d geometry makes me sad
29:42
3Blue1Brown
Рет қаралды 650 М.
My MEAN sister annoys me! 😡 Use this gadget #hack
00:24