If Else Statements - C# Mastery Course

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
you are progressing nicely now with your skill set of c-sharp and it's time to dive in and learn about a very important feature of any programming language after boolean logic which gave birth to the computer era branching statements such as even Al's gave birth to intelligent design introducing the ability to branch off our code to different outputs gives us the ability to make complex software very little code can be written without even Al statements and branching statements they are the foundations of most coding let's dive into some code and learn about even Al statements in the last lesson we made use of the tryparse method this is good and it allows us to safely attempt to convert the user's text into a valid date and if it is invalid instead of our code crashing we simply get a boolean result from the tryparse method however we now need to do something different in our code if the pass fails and return a result of it succeeds this is where the F and Al statements will come in we know now that this value succeeds boolean will be true if the parse succeeds if that is the case we should return the value to do this let's write an if statement the if statement starts with the keyword if and then open closed parentheses inside the parentheses as expected a boolean result we can type an expression directly inside of here that evaluates to a boolean result or we can give it a variable such as our succeeds variable so let's do that now we open curly braces anything inside of these curly braces will run only of this statement evaluates to true so it reads quite naturally if this statement is true then the code block here will execute otherwise we'll evaluate this as false and then move to the next line of code and never run the code inside of these curly braces in here if this is successful we simply want to return the past date that contains the actual value so we can tie for return past date so right now our logic will say ask the user for their date of birth try and pass the date of birth into a date time offset value if it is successful return the past date if it is not this code is never run and the code step to this next line which actually does exactly the same thing right now which is to still return in the past date of course the tryparse method will still set this value on failure if we open and close the parentheses go over to the second parameter and we can see that it says date time offset dot min value if the conversion fails so simply if this conversion fails it will have the value min value which is also the same as we set it by default this is not ideal because we have asked the user for their date of birth we don't want to be returning an invalid date time that the user has not entered but right now this code flow returns the same value instead we want to do something else if they enter an invalid date so let's step back a moment and write some generic if-else statements in the main method let's do the matrix test let's ask the user a question and read their answer now let's simply output two different statements based on that answer we won't do any specific validation or protection we will simply ask to check whether they have typed red blue or anything else we can route the if statement like before and output some text if they enter ret now what if their answer was not read and we want to check of it was blue we could write another statement like this and as usual a great way to learn as to debug add a breakpoint to the if statement run the program with f5 let's type read and press Enter step over this line with f10 and because we entered red so this evaluates to true notice the debugger now goes inside of this code block and outputs our message we can see this in the console window if we keep stepping over we will notice the next statement as run it checks the if statement for if the pill is blue and because it is false the code inside of the curly braces of that if statements do not run so we have our logical branching going on but only one way if something is true the code runs and then again if something is true the code runs we are doing too many checks here as the first statement checks if the pill is red and it is then the second statement can never be true the string cannot be both red and blue at the same time so we are running this expression check or possibly this expression check for no reason this is where else comes in else can be used as the name suggests to only run the expression condition if the previous airport else has evaluated to false let's change our second if statement and put the keyword else in front of the if so now it says else if press f5 to run the code again type read and press ENTER press f10 to step over and notice that this code runs again as before and the key point now is when we pressed f10 before on this line it would jump to the next if statement here and evaluate this expression let's press f10 this time and notice that this entire block including the if statements and expression was bypassed this code never ran this is an important thing to remember because when we get to class e's reference types and no references for example knowing that if the check above succeeds that the check below will never run is important to prevent things like no reference exceptions it is also more efficient to do than having superfluous double checks so you might now ask when would you use two if statements instead of an if an else statement the answer is pretty simple based on what we have just learned if the two statements could both be true at the same time then we should use if statements if there is only one possible outcome then you should use an if-else statement because the user can choose red or blue but not both there is only one outcome so we will use the if-else statement but hold on let's run our code once more I'm going to enter purple let's step over the code notice the first check evaluates to false so now the second if is evaluated and that also fails so now our program continues at the next line effectively displaying no information to the user and carrying on as if nothing has happened what do we do if we want to handle the unlimited number of possible answers from the user and present them with some kind of answer let's hope we don't have to write every possible combination of tax and millions of if statements to cover every possible outcome thankfully that is not the case we can just add another statement below this time however we are simply going to leave off the if we are going to write else only and open and close the curly braces there's no parentheses no expression to evaluate this means that if all the above checks of ifs and al saves fail then the final else statement will run inside here let's display another message telling the user they have to choose let's press f5 to run the program again and enter purple press f10 to step over the to even else if statements and notice the code then jumps straight to our else code block and outputs the code inside of this block that's great so hopefully you can see from this little test how powerful the a of an else if statements are and this is just the basics of how to use them let's go back to our code now and think about the problem and if the if-else statements can solve this problem for us right now we ask the user for their date of birth we check if it's valid and if it is we return the right value if it's not what do we do we should really tell the user to enter it again until they enter a valid date because our method is expected to return a date and we only have two real options to do this successfully we continue to ask the user indefinitely until we get the right answer or we throw an exception to escape from our method we will come to exception throwing and when we do that in a future lesson but for now we want to create an infinite loop until the user enters a valid date using what we learned with the eval statements let's see if we can solve this that's right else and as you can see here now the code obviously is exactly the same if we are successful we turn the date if we fail we turn the date so instead I'm going to do something different let's see if you can get your head around this bit of code if we just output to the user we did not enter a valid code notice our method name is red hovering over that it tells us not all code paths we turn a value the code path is the possible options this method can take if we went through and debug the code you would see it would step onto this line then this this this and this and then here is where we would create a code path as I have been calling them a branch so if we got to this if statement and it was true one path the code could take is into here this path returns a value to the method however if that's false the code path that the method takes goes into here as we have no return here and also if we continued after the else statement down to this bracket here there is no return this code path which is a possible way the method could run does not return anything because the method must return the value it's expecting or throw this is invalid code if we compile with control shift and B you can see it will not compile we have to return a value so we must return a value in this out statement here's what I'm going to do any idea is what you think is going on here let's break this down you can see firstly compiling the code now succeeds and this will run so what is happening if the user enters the right date of birth the code flows through here to the true and returns the correct date if it fails however it flows through here runs into here and then calls itself so this return method wants to return the value that comes from the method but this method is the method we are in so what does the code do does it just jump back to the start of this method not quite what we are doing here is calling this method again a method can call itself not a problem this is far beyond the knowledge of this lesson and what you have learned so far however let's just debug this for a moment so at least you get a taster of what's to come place a breakpoint in the out statement and run the code an enter an invalid date now press f10 to step over the console.writeline and see that we have now told the user you did not enter a valid date now let's press f11 to step inside of this call and you can see our code appears to have jumped back to the start of the ask for date of birth method our code has not just magically reversed itself and stepped back in time up to here instead the current method that we were in has been pushed onto the call stack further down and a new copy of this method is now at the top of the call stack once this method returns a value it will return the method to the other ask for date of birth method that was called previously check out the call stack window in the bottom right we will cover this in future lessons but the yellow arrow is where the code currently is and is symbolized by the yellow arrow in the editor you can see above that is another call for ask for date of birth and above that is the main method going from bottom to top is the order in which the code is executing and stepping down into methods we will cover all this in future lessons but just note this I'm not going to go into depth about it but watch what happens when we enter an invalid date over and over so let's let this code run it will simply continue to ask the user for the date of birth again we enter an invalid date the same logic runs its invalid and it calls the method again and asks for another date of birth and we enter invalid again but look at the call stack now we now have three calls to the same method and this is adding in words over and over the method calling itself then calling itself again and then calling itself again for this reason it is not a good way to solve the problem the call stack is limited and eventually if the user entered the date of birth wrong many times the program would crash with the infamous stack overflow exception ever wonder why Stack Overflow is called what it's called it's because it was a very common system crash in the 80s for programmers having recursive books and causing infinite loops in their code just to show you this I'm going to stop the code and at the top of this method simply return itself put a breakpoint here and press f5 to run the code and if we just press f5 over and over you can see every time we press f5 this method comes in it calls itself it goes to the start of the method calls itself again and we get effectively an infinite loop with this call stack increasing over time if I remove this breakpoint and press f5 this program will continue to run over and over and over as fast as it can and let's see what happens now you can see we get the stack overflow exception and if we take a look at our call stack we can see it's filled completely with the same call run over and at the bottom the maximum number of stack frames support it has been exceeded this is just visually inside of the core stack here but there are many many many calls to the same method there are thousands of calls that is what would happen if the user manually entered the wrong data over and over anyway I digress into future lessons here let's just leave our code as it is for now as it works and it forces the user to enter the right date of birth let's press f5 with no breakpoints and have a go we can see it asks for a date of birth I'm going to enter now and you can see it then says you did not enter a valid date and simply ask the question again I can continue to tap the wrong answer until eventually I enter a correct date and the program then successfully finishes of course we do nothing with this information yet so it's simply closes but our program works although we know them as a potential book but to fix this kind of recursive requirement that our method has whereby we want to continue to ask the user until they enter the right date we need a different kind of statement we are going to solve that a different way in the next lesson
Info
Channel: AngelSix
Views: 3,284
Rating: undefined out of 5
Keywords: c#, software, development, wpf, vue, vue js, animation, web design, wevb, .net core, asp.net core, free, open source, git, tutorial, beginners, real world, javascript, html, css
Id: 4MIZnbroRWE
Channel Id: undefined
Length: 19min 2sec (1142 seconds)
Published: Sat May 02 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.