How To Use Recursion in C#

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

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

  • @technovikingnik
    @technovikingnik 2 месяца назад +9

    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 месяца назад +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 7 дней назад

      @@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 месяца назад +20

    I would like to have the ability to talk for 20 minutes about the recursion.

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +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.

  • @darylbeaumont8855
    @darylbeaumont8855 2 месяца назад +4

    'To understand recursion, you must first understand recursion.'
    Joking aside, nice video and +1 for not using a math example!

  • @Ragnovlod
    @Ragnovlod 2 месяца назад

    Cool. Just yesterday I worked around a situation that could otherwise have been handled by this. Thanks Tim!

  • @rufarokatsamba2093
    @rufarokatsamba2093 Месяц назад

    Thanks Tim, the example used is more relatable

  • @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 👍

  • @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.

  • @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 месяца назад +1

      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 месяца назад +1

      ⁠​⁠@@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 месяца назад +1

      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!

  • @kumar315
    @kumar315 2 месяца назад +1

    Great video, thanks...can you please do a video on yield return keyword

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +1

      Done: ruclips.net/video/AAz8q6dOCYk/видео.htmlsi=2YfMEdeIwp7TFrFw

    • @kumar315
      @kumar315 2 месяца назад

      @@IAmTimCorey thankyou, you are awesome 😎

  • @Zakaria_TheWolf
    @Zakaria_TheWolf 2 месяца назад

    Amazing Lesson ✅

  • @ademineshat
    @ademineshat 2 месяца назад

    Great. 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 !!

  • @melk48111
    @melk48111 2 месяца назад

    nicely explained.

  • @conradjacobs3018
    @conradjacobs3018 2 месяца назад +4

    In order to understand recursion you have to understand recursion…

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +2

      That’s why you should understand recursion.

    • @conradjacobs3018
      @conradjacobs3018 2 месяца назад +1

      @@IAmTimCorey but to understand recursion…

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +4

      I've got a video that could help you understand it better: ruclips.net/video/fCoQP7fFqow/видео.htmlsi=9ELP8l-shAzd82sM

  • @oliverjohnson2160
    @oliverjohnson2160 2 месяца назад +1

    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 месяца назад +1

    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 месяца назад +1

      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 месяца назад +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.

  • @MartinKramer-ff5mt
    @MartinKramer-ff5mt 2 месяца назад +1

    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);
    }
    }
    }

  • @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: ruclips.net/video/fCoQP7fFqow/видео.htmlsi=rSqQxnh3wqIlwuKE

  • @_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 месяца назад +1

      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.

  • @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 месяца назад +4

      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 месяца назад +1

      Just need to Uncheck "Do not use Top-level Statements" during project setup.

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +3

      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: ruclips.net/video/aSNqqZqYTk4/видео.htmlsi=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.

  • @oragnerby
    @oragnerby 2 месяца назад

    First

  • @smeaden8947
    @smeaden8947 2 месяца назад +2

    Please don't do this.

    • @IAmTimCorey
      @IAmTimCorey  2 месяца назад +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.

  • @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 месяца назад +3

      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