0:00 - Intro 1:10 - Creating console app 1:58 - What is Yield in C# 2:34 - Writing demo code 8:03 - Demo code result analysis 9:56 - How to use Yield 13:07 - Debugging Yield 16:55 - Benefit of using Yield 20:01 - Limiting Yield returns 31:57 - Iterating collection of IEnumerable 36:41 - Why not to Yield results to List 41:21 - Summary and concluding remarks The number 4 in the list of primes is criminal.
I noticed in your demo that the number "4" was being returned in the answer set. I found that t.he problem was in the FOR loop in IsPrimeNumber. It should read: for (int i = 2; i
@@DasTagwerk var primeNumbers = Generators.GetPrimeNumbers().Skip(1).Take(10000); Fixed like a true programmer ... edit: Do not run tests with number 1 in mind though ... lul
Better is: int maxDivider = Math.Floor(Math.Sqrt(value)) + 1; for (int i=0; i < maxDivider; i++) {...} I don't know what better to name a variable in this case.
@Onedev Actually in video you have like three examples :) And if you actually watched this then you know that it can be pretty usefull when dealing with larger collections while you need only some part of it. Like, you create stuff you want from this list on the fly - you don't need to generate whole collection before you get to the item you want
mostly it is good to know what keys are pressed ,, sometime you confirm the same like cw tab tab, this can be improved in teaching with software like carnac, that removes the explicit telling what keys are pressed, as the same is shown in side of screen and user can pause and see the keys when in doubt what keys are pressed to achieve certain action.
I should probably move on, but if I have a Linq2SQL DataAccess, is the linq-based data querycouple with a .ToList not so much of an issue as described towards the end of the video? I know there's an amount of WHERE setting in the SQL, based on the LINQ but I'm just wondering if there would be any benefit to yielding linq2sql?
Since no one of us designed linq2sql that's quite hard to answer but since you're pulling Data from a Database yielding should benefit in most cases. When you're using a function that is leading to results like ToList() or Single() linq2sql trys to execute most of your linq expression or linq function-chain as sql. A result set is created in memory and non sql translatable functions are executed on that memory copy. After that you get the result subset that is the result you're working with in code. using yield form here on has no benefit at all since everything is already in memory. BUT! using yield in the linq expression or the function-chain will benefit as long as it's fitting the linq2sql concept. So if you're using extension methods heck yes use yield. If you're working with an IQueryable or equivalents probably use yield. unless it's obviously cached and there is no existing linq function that helps you around. if it's all about performance you should probably work with optimized self-written sql, stored procedures and decisions on server/client workload but that's time expensive and kind of nerdy.
Thank you Mr. Corey, I was wondering if a case use of yield could be an application that reports the percentage of advance. For example, if the app has 20 steps and each of these steps is time-consuming, yield could send a notice of the advance, so the user knows that the app is still working.
That sounds more like a gRPC connection. Yield can do it, but you need to keep asking it for more information. A gRPC connection can send data when it gets it.
Calling an API should always be asynchronous, which means it should not block your UI. Using yield wouldn't change that. I would recommend that you look at your underlying UI to figure out why you are being blocked. Maybe you forgot to call an API method using async.
Sounds like one of those somewhat more "out there" things that doesn't come up a ton, but does for certain things. Comes up a lot working with games (like in Unity), just like quaternions, which... I can't imagine I'd hear of them anywhere else but maybe something related to gimbal lock, which I also would never hear about if I didn't have to look up quaternions. lol.
I am here because i am trying to understand what IEnumerable , IEnumerator and yield keywords does.I am using Unity too, I use coroutines a lot and I came to a conclusion that Coroutine method does what Tim did here(Correct me if i am wrong) .You can select object one by one and do whatever you want with them. You can delay things in seconds via new WaitForSeconds or call after some actions to be done via WaitWhile and WaitUntil(they should be func delegate).I realised that it would be ok if i didnt struggle a lot on IEnumerator but it is always fun to look under the hood. Quaternions are always used for rotations .They are quite useful when you should rotate or orient an object and prevent your object from having gimbal lock.
So I’ve read all these comments. So far everybody looks at yield as more of an experiment. And nobody’s really using it in code in a useful way. I’m waiting for the comment where someone says “you’d be crazy not to use yield in this instance”
It is a limited-use tool. A specialty item. I covered some practical uses in this video, and there are more, but there aren't hard and fast use cases that you will always need yield for, though.
In Unity , Game Developers use yield return new waitForSeconds a lot.Thats why i am here to learn where it comes from and i realized that i dont have to do anything extra.Unity takes care of it for me.
Is it okay if I call ToList after I do my computational work in entity framework or should I exclusively work with IEnumerable all the way through my app?
Anyone noticed 4 was printed while it was not a prime number, that happened because the loop started at 2 which was equal to 4/2. So the condition wasn't met and it returned true. Which is why I have horrible anxiety that I might have screwed up my code even after thorough testing.
Have you thought of creating short videos instead of these massively long videos? Not everyone has time and would be great if you could pack the concept in under 10 minute videos. Thanks!
Others offer those type of videos. If you know exactly want you want, those are fine. Tim is targeting his videos for those looking to learn the topic in more dept. He also tries to orient the topic in real world situations.
@@tomthelestaff-iamtimcorey7597 I don’t think so, that video is about working with text files , tt files or t4 templates are usually temple files that can generate c# code at run time or design time
I have watched 5-6 videos about IEnumerable, IEnumerator, yield , ICollection , IList etc. before i saw your video. None of them were crystal clear to me. After i watched this, I stood up and clapped you cause of what you did here. You are straight to the topic and great teacher. THANK YOU
@@IAmTimCorey it sure is. I turned some code that was a big list of async operations that issued multiple events as they executed, in to a set of generic handlers that were created from a factory and made the execute method return a IAsyncEnumerable so that the events raised can be generated as a sequence and despatched. It is a thing of beauty.
Could also skip all the even numbers in the GetPrimeNumbers() method, except for 2. The first line can be "yield return 2;". The counter can then be started from 3.
Wouldn't this also be an example of a decorator? You wrap something in something else, just to extend it's functionality. Something that gives back infinite numbers gets wrapped in an enumerator which will count to 10 and then discard correct? Or does LINQ use some other magic under the hood?
@IAmTimCorey Do you have any articles or reads on that? I've been looking for a clear example of what linq does for a while now, but I can't for the life of me get a clear example
Hi Tim, thanks for all the great videos, it is easy to understand and I learned very easy and fast the single topics I'm looking for. I use yield in the game development, using unity engine (c# scripting), when you great game objects, over and over again, thru the game time, you can create new objects and destroy the once you don't need any more, this helps to keep the memory only with game objects you really need and of course with creating them on run time, it speeds things up
I wonder what would happen if yield were used inside an async/await operation. I also wonder if yield would/could ever be used with Entity Framework and IQueryable. I'm having a difficult time visualizing yield being used in CRUD operations, even in reads where you just get something and display it. It doesn't sound useful in those situations. Am I missing some things?
Excellent video. Yield was one of those gaps of knowledge I had for a long time. Can't think of a scenario where I could use it yet, but I am sure I will consider it in the future.
How can we use this in the case of pagination? Say when I click on next it should fetch 20 records per page, dynamically without duplicating the code. Thanks
When I press Result View, I do not get the error message, instead it suddenly instantiates all the people, regardless of debugging. I THINK this might be because of the newer C# version or Visual Studio 2022. So it seems this has changed. It confused me for a bit.
@@IAmTimCorey Hi! Thanks for replying. I just downloaded your source code and on line 13 removed to Take(2), so just: var people = DataAccess.GetPeople(); I started debugging and when I checked the Result View of people in debug mode it once again instantiated all 3 people, and logging them to the console. If I don't check the result view, it will have the wanted result, so only instantiating them one at a time in the foreach section. I am using Visual Studio Community 2022 V 17.2.0
Instead of doing while(true) you should use while (counter < int.max) simply because even with the yield, eventually you WILL overflow and throw an exception if the yield is called enough times. Also once the loop breaks the next count will start over at the first number if it does overflow instead of just burning the application in overflow exception fire. Though still do NOT use that without the yield people, it will basically lock up and run forever essentially like while(true) would it just won't overflow and kill the app.
In this case, we will never reach an overflow state. Instead, we will reach a computational limit trying to compute that large of a prime number. Changing to the evaluation won't change that so the comparison is not necessary, and it adds overhead.
I've never wrote a program using yield but I had to work on one written by someone else. This program compared files in two folder structures and copied the files that were different from the source folder to the destination folder. Having never seen this before, I stepped through the code with breakpoints. The order of the calls was really weird to me at first (still is I guess, lol) but then I saw that this way was a lot more efficient than reading everything to to a list and then operating on the list. Great explanation Tim!
Hi Tim, THX for your explain. Its how ever great!! But i have a Question. How can I use the yield Iterator over the Network. With REST or everything else. Can you explain more of this topic? THX Marcus
This is a safety check to be sure we can move next. The "infinite" prime number method should never return that if it is being called without modifiers but if we limit it to be called only a certain number of times, it would run out of times at that point and not be able to move next. For instance, if in this case we had limited the call to 5 times, it would hit the break before the end of the loop.
@@IAmTimCorey Beg your pardon, but I didn't understand you. The decision whether to break or not is controlled solely by "MoveNext()" method. Where were you about to put the limit (as you said - 5 times)?
There is a mistake here, I'm no mathematician but (4) is not prime number :) Good session though your method of explaining and teaching is amazing Thanks sir...
It isn't terrible, but as I stated in the video, it isn't the best. That wasn't the goal. The goal was to have a bit of code where it made sense to call it repeatedly but where we could not efficiently anticipate how many times it needed to be called.
Feature 'target-typed object creation' is not available in C# 7.3. Please use language version 9.0 or greater! Got this error from the line List output = new(); But showed the output!! 🤔
yield return is a very powerful piece of functionality. Do upon request; not do upon load which in some instances can be great. But this is definitely also something that needs to be used with care and consideration, because it does a lot of things while looping through that foreach()-loop, and if you do multiple nested loops this could potentially slow down things than one might expect, particularly if you're working with recordsets from a database, etc. And Corey, you've gone done the perfect Terminator imitation! It will not stop. EVER -- until your PC is idea! Do you want to kill somebody's computer with that while()-statement? ;-) It's not gonna kill the PC, I know, BUT it's gonna be a busy bunny for a bit -- without the yield return. ;-)
The code that the yield executes is no different than "regular" code in how you work with it. If you do lots of nested loops, that's going to be an issue whether you are yielding the results of the top loop or not.
@@IAmTimCorey Oh, I know. I was referering to doing what you were coding inside nested loops. Nested loops is ALWAYS a performance issue, especially when they are forever enduring.
You should have went into more about how paging works. How does the server remember where to resume if the second page is loaded with a REST API. Also going over the Skip Linq command would have been helpful to show new users.
@@IAmTimCorey I think Skip is an important distinction here because it still creates/calculates the objects even though they are skipped. Also ILspy could help here, to give people a way to debug their code better.
It may be, but must not. IEnumerable is just an Instance of something you can iterate through like a set, an array or a list. so your Vector class from c++ would probably implement IEnumerable if and only if it was c#
0:00 - Intro
1:10 - Creating console app
1:58 - What is Yield in C#
2:34 - Writing demo code
8:03 - Demo code result analysis
9:56 - How to use Yield
13:07 - Debugging Yield
16:55 - Benefit of using Yield
20:01 - Limiting Yield returns
31:57 - Iterating collection of IEnumerable
36:41 - Why not to Yield results to List
41:21 - Summary and concluding remarks
The number 4 in the list of primes is criminal.
Thanks for the work. Folks love this type breakdown.
lol. Yeah the 4 is because he did 'less than' instead of 'less or equal to'. Edit: Also, isn't 1 not a prime number either?
2 years ago I watched my first programming videos here, it has been my hobby since, everyday. Thank you sir for changing my life.
Excellent!
Also exclude 1,
if (IsPrimeNumber(counter))
{
if (counter != 1)
{
yield return counter;
}
}
Thanks Tim for another great video!
Yeah the IsPrimeNumber function is flawed, cause it spits out 4 but 4 is no prime number (can be divided by 1, 2, 4)
I noticed in your demo that the number "4" was being returned in the answer set. I found that t.he problem was in the FOR loop in IsPrimeNumber. It should read:
for (int i = 2; i
Yep, that one bugs me. Oh well.
And you have to exclude 1 - it’s not a primenumber
@@DasTagwerk
var primeNumbers = Generators.GetPrimeNumbers().Skip(1).Take(10000);
Fixed like a true programmer ...
edit: Do not run tests with number 1 in mind though ... lul
Better is:
int maxDivider = Math.Floor(Math.Sqrt(value)) + 1;
for (int i=0; i < maxDivider; i++) {...}
I don't know what better to name a variable in this case.
That 4 was bothering me. Ha ha.
I love how to you explained it's very clear for me thank you
@Onedev Actually in video you have like three examples :)
And if you actually watched this then you know that it can be pretty usefull when dealing with larger collections while you need only some part of it.
Like, you create stuff you want from this list on the fly - you don't need to generate whole collection before you get to the item you want
Glad it was helpful!
Too good explanation Tim. Keep it up! Thanks!
You are welcome.
mostly it is good to know what keys are pressed ,, sometime you confirm the same like cw tab tab, this can be improved in teaching with software like carnac, that removes the explicit telling what keys are pressed, as the same is shown in side of screen and user can pause and see the keys when in doubt what keys are pressed to achieve certain action.
I should probably move on, but if I have a Linq2SQL DataAccess, is the linq-based data querycouple with a .ToList not so much of an issue as described towards the end of the video?
I know there's an amount of WHERE setting in the SQL, based on the LINQ but I'm just wondering if there would be any benefit to yielding linq2sql?
Since no one of us designed linq2sql that's quite hard to answer but since you're pulling Data from a Database yielding should benefit in most cases.
When you're using a function that is leading to results like ToList() or Single() linq2sql trys to execute most of your linq expression or linq function-chain as sql. A result set is created in memory and non sql translatable functions are executed on that memory copy. After that you get the result subset that is the result you're working with in code. using yield form here on has no benefit at all since everything is already in memory.
BUT! using yield in the linq expression or the function-chain will benefit as long as it's fitting the linq2sql concept.
So if you're using extension methods heck yes use yield.
If you're working with an IQueryable or equivalents probably use yield. unless it's obviously cached and there is no existing linq function that helps you around.
if it's all about performance you should probably work with optimized self-written sql, stored procedures and decisions on server/client workload but that's time expensive and kind of nerdy.
Thank you Mr. Corey, I was wondering if a case use of yield could be an application that reports the percentage of advance. For example, if the app has 20 steps and each of these steps is time-consuming, yield could send a notice of the advance, so the user knows that the app is still working.
That sounds more like a gRPC connection. Yield can do it, but you need to keep asking it for more information. A gRPC connection can send data when it gets it.
Thanks a lot for your answer, it means a lot to me.
can this be used from a API to a C# WASM so it can render while downloading and dont block the UI?
Calling an API should always be asynchronous, which means it should not block your UI. Using yield wouldn't change that. I would recommend that you look at your underlying UI to figure out why you are being blocked. Maybe you forgot to call an API method using async.
Sounds like one of those somewhat more "out there" things that doesn't come up a ton, but does for certain things. Comes up a lot working with games (like in Unity), just like quaternions, which... I can't imagine I'd hear of them anywhere else but maybe something related to gimbal lock, which I also would never hear about if I didn't have to look up quaternions. lol.
It isn't something you will use often, but when you need to use it, it will be really helpful.
I am here because i am trying to understand what IEnumerable , IEnumerator and yield keywords does.I am using Unity too, I use coroutines a lot and I came to a conclusion that Coroutine method does what Tim did here(Correct me if i am wrong) .You can select object one by one and do whatever you want with them. You can delay things in seconds via new WaitForSeconds or call after some actions to be done via WaitWhile and WaitUntil(they should be func delegate).I realised that it would be ok if i didnt struggle a lot on IEnumerator but it is always fun to look under the hood.
Quaternions are always used for rotations .They are quite useful when you should rotate or orient an object and prevent your object from having gimbal lock.
Hi tim can you make sperate play list on multi threading in c# I have more confusion🤔🤔🤔
I added it to Tim's list for topics to consider. Thanks for recommending it.
Tim I’m confused on how to use yield with dapper when using query async , or over api end points that returns json data !
Did you find out?
minute 19 is the most important minute
Good to know.
how do you handle Resharper warning of multiple enumeration (when using IEnumerable)?
I don't use Resharper. It sounds like a setting that needs to be tweaked, though.
So I’ve read all these comments. So far everybody looks at yield as more of an experiment. And nobody’s really using it in code in a useful way.
I’m waiting for the comment where someone says “you’d be crazy not to use yield in this instance”
It is a limited-use tool. A specialty item. I covered some practical uses in this video, and there are more, but there aren't hard and fast use cases that you will always need yield for, though.
In Unity , Game Developers use yield return new waitForSeconds a lot.Thats why i am here to learn where it comes from and i realized that i dont have to do anything extra.Unity takes care of it for me.
Is it okay if I call ToList after I do my computational work in entity framework or should I exclusively work with IEnumerable all the way through my app?
It depends on the situation but usually yes.
Anyone noticed 4 was printed while it was not a prime number, that happened because the loop started at 2 which was equal to 4/2. So the condition wasn't met and it returned true. Which is why I have horrible anxiety that I might have screwed up my code even after thorough testing.
Have you thought of creating short videos instead of these massively long videos? Not everyone has time and would be great if you could pack the concept in under 10 minute videos.
Thanks!
Others offer those type of videos. If you know exactly want you want, those are fine. Tim is targeting his videos for those looking to learn the topic in more dept. He also tries to orient the topic in real world situations.
I kind of know what you mean though even though we love Tim!
Do you have any videos on run time and design time templates aka those tt files
Not sure if they are covered in this or not. - ua-cam.com/video/cST5TT3OFyg/v-deo.html
@@tomthelestaff-iamtimcorey7597 I don’t think so, that video is about working with text files , tt files or t4 templates are usually temple files that can generate c# code at run time or design time
@@captkalik OK, I have added it to Tim's list of viewer suggestions for his consideration. Thanks for sharing and clarifying.
@@tomthelestaff-iamtimcorey7597 awesome thanks
what i need to config in order my VS2019 add the paremeter "value" by it self?
Tim has several videos on Visual Studio - ua-cam.com/users/IAmTimCoreysearch?query=visual
@@tomthelestaff-iamtimcorey7597 that doesn't help. I you know the answer or the video just tell me.
@@maestrowilliam I do not know which video nor do I know which setting. I wish you luck.
4 is not a prime number....
I forgot to turn on the bug zapper and one got through.
Let me say, you DO make learning C# easier sir, thank you so much for making these videos, you can't imagine how much your videos help.
I appreciate the kind words. I am glad my content has been helpful.
I have watched 5-6 videos about IEnumerable, IEnumerator, yield , ICollection , IList etc. before i saw your video. None of them were crystal clear to me. After i watched this, I stood up and clapped you cause of what you did here. You are straight to the topic and great teacher. THANK YOU
I am glad it was helpful.
IAsyncEnumerable and yield... that is where it is at.
That is a powerful combo.
@@IAmTimCorey it sure is. I turned some code that was a big list of async operations that issued multiple events as they executed, in to a set of generic handlers that were created from a factory and made the execute method return a IAsyncEnumerable so that the events raised can be generated as a sequence and despatched. It is a thing of beauty.
I kind of think the yield functionality was added just so employers could use it as a trick question for interviews =)
lol there are reasons for it. It just isn’t an everyday thing.
Haha exactly, I had one
I wish you covered .Skip() since it has some relevance with .Take() . Very informative and nice work
Thanks!
If I do .Skip(10).Take(15) will that be as efficient as the iterator version?
@@streammxc It will work the same as iterator.
For those running low power computers: you can make the for loop signature for(int i = 2; i
Thanks for the tip
Could also skip all the even numbers in the GetPrimeNumbers() method, except for 2. The first line can be "yield return 2;". The counter can then be started from 3.
public static IEnumerable GetPrimeNumbers()
{
yield return 2;
int counter = 3;
while(true)
{
if (IsPrimeNumber(counter))
yield return counter;
counter+=2;
}
}
27:30 - are you shure, that 4 is a prime number?)
lol, I missed an equals in the method. Hate it when that happens.
@@IAmTimCorey Also, technically, 1 is not considered a prime number. 2 is the first (and only even) prime.
@@DJDoena wow, so smart
Wouldn't this also be an example of a decorator? You wrap something in something else, just to extend it's functionality. Something that gives back infinite numbers gets wrapped in an enumerator which will count to 10 and then discard correct? Or does LINQ use some other magic under the hood?
Not really. As for what LINQ is doing, it is basically setting up a state machine.
@IAmTimCorey Do you have any articles or reads on that? I've been looking for a clear example of what linq does for a while now, but I can't for the life of me get a clear example
Thanks for the video Tim. Don't you have a bug in your function? It returns number 4 within your prime numbers.
Yep, the method is missing an equals sign.
in my visual studio this console.writeline(value:"string"); the word "value" is not showing, how to enable it.
One should really clamp numeric iterators with the types MaxValue even for demo code or especially so perhaps?
Youre the best tutor ever☺️
Thanks!
Thanks. Learned about something new today! :)
You are welcome.
Hi Tim, thanks for all the great videos, it is easy to understand and I learned very easy and fast the single topics I'm looking for. I use yield in the game development, using unity engine (c# scripting), when you great game objects, over and over again, thru the game time, you can create new objects and destroy the once you don't need any more, this helps to keep the memory only with game objects you really need and of course with creating them on run time, it speeds things up
Great video, as ever... But 1 isn't a prime number :)
Hey Tim just wondering how you get the value: and count: hints in the code? I'm not sure I've ever seen that default in my code.
Did you find out?
Enable Code Lens in VS.
Thanks, useful video, for secound 15 prime number you could do something like this take(15).skip(10) and 10 is the count of the list so far
Thanks for sharing.
greetings and appreciation from Kazakhstan!!!(i d'know, you've heard about Kazakhstan at all))) )
Hi from Texas.
You're my guide in C-Sharp dr.Tim .. No word could express our gratitude to you >> THANK YOU
You are welcome.
Since when is 4 a Prime?
Since I forgot the equals in the check.
Since we're on the subject, 1 is not prime either.
Using Yield is just lazy.
Sorry, I couldn't help myself.
lol
You sound different from your tutoriala and when you talking and showing your face on camera
It is the same mic for both in the videos from this year. Interesting.
Thanks
Thank you from the whole team at IAmTimCorey
Everything is clear now. Thanks a million!
You are welcome.
4 is not prime, I was wondering where I went wrong then noticed you made a mistake in a for loop.
Yep, forgot the equals.
What option flag do you have set to show the argument names for methods being called (e.g. value for Console.WriteLine)?
You must have VS2019 - v16.8 and above .. Tools > Options > Text Editor > C# or Basic > Advanced and select Display inline parameter name hints
In VS settings:
Text Editor > C# > Advanced > Display inline parameter name hints
I wonder what would happen if yield were used inside an async/await operation. I also wonder if yield would/could ever be used with Entity Framework and IQueryable. I'm having a difficult time visualizing yield being used in CRUD operations, even in reads where you just get something and display it. It doesn't sound useful in those situations. Am I missing some things?
pure programming goodness without all that hipster bullshit of other channels
Thanks.
great sir,
i've a question, why.. if i put counter++ inside the if statement with yield return init, the console crash suddenly
Excellent video. Yield was one of those gaps of knowledge I had for a long time. Can't think of a scenario where I could use it yet, but I am sure I will consider it in the future.
I’m glad it was helpful.
Have you found a scenario yet?
How can we use this in the case of pagination? Say when I click on next it should fetch 20 records per page, dynamically without duplicating the code. Thanks
Could you also show, how to make a real application? Why use just var and not int, double etc.?
When I press Result View, I do not get the error message, instead it suddenly instantiates all the people, regardless of debugging. I THINK this might be because of the newer C# version or Visual Studio 2022. So it seems this has changed. It confused me for a bit.
Are you using my code that you downloaded? It may be a slight difference compared to my code if you typed it yourself.
@@IAmTimCorey Hi! Thanks for replying. I just downloaded your source code and on line 13 removed to Take(2), so just: var people = DataAccess.GetPeople(); I started debugging and when I checked the Result View of people in debug mode it once again instantiated all 3 people, and logging them to the console. If I don't check the result view, it will have the wanted result, so only instantiating them one at a time in the foreach section. I am using Visual Studio Community 2022 V 17.2.0
@@Voodookillers This is really strange, i get the same "Issue" cool that you also pointed it out.
another GEM from dear uncle Tim.
Thanks!
1 is not prime. Dislike, unsub. JK
lol
Instead of doing while(true) you should use while (counter < int.max) simply because even with the yield, eventually you WILL overflow and throw an exception if the yield is called enough times. Also once the loop breaks the next count will start over at the first number if it does overflow instead of just burning the application in overflow exception fire.
Though still do NOT use that without the yield people, it will basically lock up and run forever essentially like while(true) would it just won't overflow and kill the app.
In this case, we will never reach an overflow state. Instead, we will reach a computational limit trying to compute that large of a prime number. Changing to the evaluation won't change that so the comparison is not necessary, and it adds overhead.
1:16 Blazor Server supremacy 🙌
👍🏻
I've never wrote a program using yield but I had to work on one written by someone else. This program compared files in two folder structures and copied the files that were different from the source folder to the destination folder. Having never seen this before, I stepped through the code with breakpoints. The order of the calls was really weird to me at first (still is I guess, lol) but then I saw that this way was a lot more efficient than reading everything to to a list and then operating on the list.
Great explanation Tim!
Thanks!
Hi Tim, THX for your explain.
Its how ever great!!
But i have a Question.
How can I use the yield Iterator over the Network. With REST or everything else.
Can you explain more of this topic?
THX
Marcus
Topic suggestion noted and have added to Tim's list of viewer requests, thanks.
I wonder why on earth you would need "else { break; }" at 35:00?
This is a safety check to be sure we can move next. The "infinite" prime number method should never return that if it is being called without modifiers but if we limit it to be called only a certain number of times, it would run out of times at that point and not be able to move next. For instance, if in this case we had limited the call to 5 times, it would hit the break before the end of the loop.
@@IAmTimCorey Beg your pardon, but I didn't understand you. The decision whether to break or not is controlled solely by "MoveNext()" method. Where were you about to put the limit (as you said - 5 times)?
27:46 yo who else noticed the four lol
Yep. I forgot an equals in the evaluation.
So useful, thank you so much
You are welcome.
There is a mistake here, I'm no mathematician but (4) is not prime number :)
Good session though your method of explaining and teaching is amazing
Thanks sir...
lol yeah, kicking myself for missing that one. You need to add an equals in the for loop to fix this.
Thank you for the information
You are welcome.
is 4 prime number? time 27:43
Nope, that's a bug in the code. We should have either checked for that specific case or done a "i
Thank you very much!!!
You are welcome.
I'm confused about how that isn't a terrible prime number checker. Skip even numbers and memo-ize that and it might be "not terrible".
It isn't terrible, but as I stated in the video, it isn't the best. That wasn't the goal. The goal was to have a bit of code where it made sense to call it repeatedly but where we could not efficiently anticipate how many times it needed to be called.
Regarding running out of memory in the GetPrime without a Yield:
Wouldn't it just return 3 each time it is called?
No, it will return a list of prime numbers but it does not know when to stop finding them. Give it a try.
why 4 is a prime number?
Because I forgot an equals in the evaluation.
Very powerful Yield
Yep.
Would you do video about REGEX/REGEXP in C#?
I will add it to the list. Thanks for the suggestion.
very nice yield demo
Thanks!
This finally clicked for me. Thank you for an awesome explanation!
Glad it was helpful!
Amazing 🤩
Thanks!
Hi Tim, should dependency injection be used for everything now?
Most things, yes. It is a very useful pattern.
Feature 'target-typed object creation' is not available in C# 7.3. Please use language version 9.0 or greater!
Got this error from the line
List output = new();
But showed the output!! 🤔
= new() is a rather new language feature. In old c# you would always write = new List()
Interesting.
yield return is a very powerful piece of functionality. Do upon request; not do upon load which in some instances can be great. But this is definitely also something that needs to be used with care and consideration, because it does a lot of things while looping through that foreach()-loop, and if you do multiple nested loops this could potentially slow down things than one might expect, particularly if you're working with recordsets from a database, etc.
And Corey, you've gone done the perfect Terminator imitation! It will not stop. EVER -- until your PC is idea!
Do you want to kill somebody's computer with that while()-statement? ;-) It's not gonna kill the PC, I know, BUT it's gonna be a busy bunny for a bit -- without the yield return. ;-)
The code that the yield executes is no different than "regular" code in how you work with it. If you do lots of nested loops, that's going to be an issue whether you are yielding the results of the top loop or not.
@@IAmTimCorey Oh, I know. I was referering to doing what you were coding inside nested loops. Nested loops is ALWAYS a performance issue, especially when they are forever enduring.
@IAMTimCorey how did you enable the class/type in visual studios? at Console.WriteLine(value: "Start of the App"); @timestamp: 7:52 ?
im talking about the "value:" part.
Here you go: ua-cam.com/video/f0YeVirKPfw/v-deo.html
What about "yield break"?
What about it?
@@IAmTimCorey I wish you explained "yield break" too, which I believe is as important as "yield return"
You should have went into more about how paging works. How does the server remember where to resume if the second page is loaded with a REST API. Also going over the Skip Linq command would have been helpful to show new users.
This video was about Yield, not APIs or LINQ which is why I didn’t cover more about those.
@@IAmTimCorey I think Skip is an important distinction here because it still creates/calculates the objects even though they are skipped. Also ILspy could help here, to give people a way to debug their code better.
Y'ALL in C#
C#, Texas edition?
Thanks!
Thank you!
Thanks
You are welcome.
GREAT!
Thanks!
Does anyone know how to switch fast between highlighted variables as Tim did at 22:14?
When you use a snippet, you can tab between different spots.
@@IAmTimCorey thank you so much!!!
Nice video. Do you have an example with SqlDatabase and Dapper?
Not yet, no.
Very very useful lesson. Thanks so much!!!!!!!
You are welcome.
Have you ever explained what a dto is and when n how to use it ?
I have noted it as a Topic suggestion and have added to Tim's list of viewer requests, thanks.
Can API endpoint return as Yeild to the caller?
Not directly but it can use yield internally so it acts the same way. Just remember that this would be for everyone, not per user.
lol @ "interator"
absolutely great explanation of the topic !!
Thank you.
gr8 vid like always, tnx a lottt keep going
prec8 the support
Is an IEnumerable a dynamic array? Like the vector class in c++?
It may be, but must not. IEnumerable is just an Instance of something you can iterate through like a set, an array or a list. so your Vector class from c++ would probably implement IEnumerable if and only if it was c#
It's kinda like implementing std::begin and std::end for use with range based for loops. A std::vector is more similar to a List in C#.
Tim Sharp and Yield is just what i needed
Great!
6:27 Ctrl+D also does the trick.
Thanks for sharing.
Hah was just reading about this, yay
Great!
amazing into to Yield
thanks man
Happy to help!
Tim you DO NOT MISS
Thanks!