- [Narrator] So far, all of our if statements have worked with only two possible paths of execution. But sometimes you have something a little bit more complicated than that. So let's add a new method to our flow control class and this one is going to work a little bit differently. This one's going to return a string, based on which color you pass in. So we'll call this one primary or secondary and we'll take a string for the color.
So what we're going to do here is we're going to take a string in for the color and if it's primary, we'll return primary, if it's secondary, we'll return secondary. To do this, we're going to use a series of if statements. And you can string them together and that's really what I'm about to show you. So we can say if color.to lower, equals red, that's a primary color, then we'll need to set some value to primary.
We could return, but let's do it this way this time. Let's do var, and we'll just call it result and I'll set it equal to an empty string for now. So if it's red, I'll say result equals primary. Now instead of an else statement, I actually need more than just two possibilities so I'm say, else if color.to lower equals blue, then we can say result equals primary.
And we've got one more, we can say else if color.to lower equals yellow, then we can say result equals primary. And if none of that is true, we're just going to assume, for the sake of the example, that it must be secondary. So we'll say result equals secondary. And then when we're done, we need to return the result.
So you can see here how we are chaining our if statements together so that we can evaluate something with more than just two possibilities. There's actually a much better way to do this but this is a good example of using if, else if and else together.
AuthorBruce Van Horn
- Writing unit tests in C#
- Working with simple and multidimensional arrays
- Managing ordered and unordered data with lists
- Evaluating conditions with if-else statements
- Using OR, AND, and NOT operators
- Building loops
- Debugging and handling exceptions
- Creating the final build of your C# project
Skill Level Beginner
C# Object-Oriented Programming Tips and Trickswith Jesse Freeman58m 39s Intermediate
1. Unit Testing and Test-Driven Development
2. Arrays and Collections
3. Flow Control
4. Exception Handling
5. Getting to Production
Next steps1m 57s
- Mark as unwatched
- Mark all as unwatched
Are you sure you want to mark all the videos in this course as unwatched?
This will not affect your course history, your reports, or your certificates of completion for this course.Cancel
Take notes with your new membership!
Type in the entry box, then click Enter to save your note.
1:30Press on any video thumbnail to jump immediately to the timecode shown.
Notes are saved with you account but can also be exported as plain text, MS Word, PDF, Google Doc, or Evernote.