How To Use Recursion in C#

  Рет қаралды 6,942

IAmTimCorey

IAmTimCorey

Күн бұрын

Recursion is a topic that is simple in its basic form but can be complicated to grasp when first starting out. It is also a topic that is important to understand as a C# developer. In this video, we are going to learn what recursion is and how to utilize it properly in an application. We will also talk about the best practices for using recursion.
Full Training Courses: IAmTimCorey.com

Пікірлер: 61
@aleksejspiscevs
@aleksejspiscevs 7 күн бұрын
I would like to have the ability to talk for 20 minutes about the recursion.
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
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.
@technovikingnik
@technovikingnik 7 күн бұрын
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 7 күн бұрын
Exactly. In the past I had to use this with Active Directory. Also use this with Feature Trees in SolidWorks custom apps.
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Thank you!
@darylbeaumont8855
@darylbeaumont8855 7 күн бұрын
'To understand recursion, you must first understand recursion.' Joking aside, nice video and +1 for not using a math example!
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Thanks!
@Ragnovlod
@Ragnovlod 5 күн бұрын
Cool. Just yesterday I worked around a situation that could otherwise have been handled by this. Thanks Tim!
@IAmTimCorey
@IAmTimCorey 5 күн бұрын
You are welcome.
@F4ir8or
@F4ir8or 6 күн бұрын
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 6 күн бұрын
Thank you!
@studentsheaven-d8v
@studentsheaven-d8v 7 күн бұрын
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 7 күн бұрын
I'm considering it.
@conradjacobs3018
@conradjacobs3018 7 күн бұрын
In order to understand recursion you have to understand recursion…
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
That’s why you should understand recursion.
@conradjacobs3018
@conradjacobs3018 7 күн бұрын
@@IAmTimCorey but to understand recursion…
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
I've got a video that could help you understand it better: kzbin.info/www/bejne/nHTSgoNtm6ukpdksi=9ELP8l-shAzd82sM
@kumar315
@kumar315 7 күн бұрын
Great video, thanks...can you please do a video on yield return keyword
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Done: kzbin.info/www/bejne/d3LdaaRsmbR2j80si=2YfMEdeIwp7TFrFw
@kumar315
@kumar315 7 күн бұрын
@@IAmTimCorey thankyou, you are awesome 😎
@kilworthman
@kilworthman 7 күн бұрын
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 7 күн бұрын
Sounds good.
@coujean99
@coujean99 7 күн бұрын
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 7 күн бұрын
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 6 күн бұрын
⁠​⁠@@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 5 күн бұрын
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 5 күн бұрын
@@IAmTimCorey Ok, I understand. Thank you for your precisions!
@Zakaria_TheWolf
@Zakaria_TheWolf 7 күн бұрын
Amazing Lesson ✅
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Thanks!
@oliverjohnson2160
@oliverjohnson2160 7 күн бұрын
Instead of depth could we have used say directories with files only as the base case for the recursion example ?
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
We did use that when we didn’t specify a depth. When the folder has no subfolders, it stops.
@ademineshat
@ademineshat 7 күн бұрын
Great. Thanks 👍
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
You are welcome.
@melk48111
@melk48111 7 күн бұрын
nicely explained.
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Thank you!
@MartinKramer-ff5mt
@MartinKramer-ff5mt 7 күн бұрын
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); } } }
@studentsheaven-d8v
@studentsheaven-d8v 7 күн бұрын
something new, will continue the C# start to finish from tomorrow.
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Great!
@K03N88
@K03N88 7 күн бұрын
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 7 күн бұрын
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 7 күн бұрын
Just need to Uncheck "Do not use Top-level Statements" during project setup.
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
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 6 күн бұрын
@@IAmTimCorey Ah.. I'm using mainly 4.8 for add-ins to connect with a program specific API. Later is not supported.
@holger_p
@holger_p 7 күн бұрын
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 7 күн бұрын
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 7 күн бұрын
@@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.
@_samirdahal
@_samirdahal 7 күн бұрын
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 7 күн бұрын
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.
@smeaden8947
@smeaden8947 7 күн бұрын
Please don't do this.
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
Why? Recursion is an important part of software development.
@ace90210ace
@ace90210ace 7 күн бұрын
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 7 күн бұрын
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 7 күн бұрын
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.
@ousmanetall1286
@ousmanetall1286 7 күн бұрын
Second
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
👍🏻
@oragnerby
@oragnerby 7 күн бұрын
First
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
👍🏻
@pl4gueis
@pl4gueis 7 күн бұрын
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 7 күн бұрын
There are plenty of methods you can use in C# to prevent stack overflows and that includes recursion. lol @ F#
@IAmTimCorey
@IAmTimCorey 7 күн бұрын
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 7 күн бұрын
@@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.
АЗАРТНИК 4 |СЕЗОН 1 Серия
40:47
Inter Production
Рет қаралды 1,4 МЛН
escape in roblox in real life
00:13
Kan Andrey
Рет қаралды 65 МЛН
МЕБЕЛЬ ВЫДАСТ СОТРУДНИКАМ ПОЛИЦИИ ТАБЕЛЬНУЮ МЕБЕЛЬ
00:20
Brutally honest advice for new .NET Web Developers
7:19
Ed Andersen
Рет қаралды 182 М.
OpenAI Releases GPT Strawberry 🍓 Intelligence Explosion!
21:21
Matthew Berman
Рет қаралды 238 М.
How IDisposable and Using Statements Work Together in C#
10:01
IAmTimCorey
Рет қаралды 31 М.
Why Are Bands Mysteriously Disappearing?
8:25
Rick Beato
Рет қаралды 794 М.
What Employers Look For When Hiring Developers
17:58
IAmTimCorey
Рет қаралды 3,6 М.
Building better DTOs in C#
11:57
Gui Ferreira
Рет қаралды 4,5 М.
WHY did this C++ code FAIL?
38:10
The Cherno
Рет қаралды 258 М.
how Google writes gorgeous C++
7:40
Low Level Learning
Рет қаралды 878 М.
Learn How To Simplify Difficult Tasks In Software Development
16:56
Proxy vs Reverse Proxy vs Load Balancer | Simply Explained
13:19
TechWorld with Nana
Рет қаралды 57 М.
АЗАРТНИК 4 |СЕЗОН 1 Серия
40:47
Inter Production
Рет қаралды 1,4 МЛН