C# Fundamentals: Development for Absolute Beginners

Branching with the if Decision Statement and the Conditional Operator - 06

Download this episode

Download Video

Download captions

Download Captions


Branching allows us to add logic to our applications. In this lesson introduces the if Decision statement (in its various forms) as well as the conditional operator. We also discuss how to refactor our code to make it more compact and less likely to produce errors by eliminating duplicate code.

Download the source code for Branching with the if Decision...


C#, Visual Studio



Available formats for this video:

Actual format may change based on video formats available and browser capability.

    The Discussion

    • santi_m

      More C# videos most welcome, this is infectious.

    • subaddiction

      I really love the careful and detailed explanations that I've watched so far.... I really cannot thank you enough!!! you saved my academics!!!!!! Big Smile Big Smile Big Smile

    • SimonMcGuirk

      Another video followed. Thanks to the team behind these. Really enjoying them and finding Bob's explanations clear and easy to follow. Also glad that he's not reading out every line of code as this gets me into the habit of reading the code before I start to type. I know what I'll be doing over the festive period.

    • nokks

      i was struggling with learning C#, i have easily understood the stuff covered in these videos, thanks a million.

    • BobTabor

      @santi_m @subaddiction @Scimac @nokks : Thank you all for the compliments.  Glad these can be of help to you!  Best wishes in 2012!

    • Ricardo

      Thank you very much for your detailed and interesting videos, I appreciate them very much!

    • susan

      Thank you for sharing your knowledge... I learn a lot on this.
      It's easy to understand and follow

    • piim

      I've been in MS software development over 10 years and I still find myself watching these. Maybe it's because the appealing way you present the concepts, or maybe because you look like Steve Martin :))

    • BobTabor

      @Ricardo, @susan: Thank you for the feedback!

      @piim: Thanks for the compliment ... I think?  Smiley  You are the third person to tell me that within the past year, so I guess I need to grow my beard back.

    • EmW

      Hats off to you, these have been so helpful. Thank you for being one of the best teachers i have encountered

    • BobTabor

      @EmW: Smiley  Thanks for the nice words.  Made my day!

    • Aamir Syed

      Thanks to these C# beginners lectures I can now sleep at night!

    • BobTabor

      @Aamir Syed: Is that a compliment?  Or do I put you to sleep?  Big Smile

    • Aamir Syed

      Sorry I did not express myself well.That was a good compliment!You see I work full time and have started learning C# at night on a limited time budget.Tried other books/sources but none drive home the basic concepts as quickly as your lectures. Cheers! Aamir

    • BobTabor

      @Aamir Syed: Hehe ... thank you for the compliment then.  Smiley  And I'm glad these videos helped you nail down the basic concepts.  Keep pushing forward ... this is fun stuff!

    • Fernando Herrera

      Thank you for your lectures, I really enjoy the simplicity and easy learning experience.

    • MorS

      Bob you made some awsom clear and simple videos , but where could we practice the skills we learning .

      could you refer us to some practice examples?

    • BobTabor

      @MorS: I have a series on my own website that has homework questions and solutions explained via video.  Check it out!

    • Davor

      This series is really god.The best I've seen so far.Will you maybe make next series?Maybe intermediate?

    • Cale Elliott

      Thank you Bob for creating these videos. Was in school for programming for 3 years and events in life drove me off the academic path for now, but my passion for programming is strong as ever. These videos (along with the enormous compendium of knowledge on the MSDN) truly helped me understand the core concepts of OOP more than any professor has been able to/willing to explain.

      Thank you again, truly appreciate the help!

    • BobTabor

      @Davor: Thanks for the nice words!  None in the works just yet.  In your mind, what topics would you want covered in an "intermediate" series?

      @Cale Elliott: Awesome, Cale.  Thanks for passing that story along ... encouraging to me. Smiley

    • Matt

      Thanks for the great tutorials so far. This is very easy to follow and I couldn't learn this anywhere else.

    • Uli

      Thanks a lot for these videos, they are amazingly well done. I'm finally starting to see I can make this while other tutorials I tried were so confusing, unstructered or too fast - was very frustrating.

    • PEDR0MEJI4

      Bob, i guess everyone said pretty much everything i could think of to display my appreciation for your videos. Makes everything so easy to understand! Not everyone can do that ~ Cheers!

    • BobTabor

      @Matt: @Uli: @PEDR0MEJI4: Thank you all for the nice words.  I'm really glad that they are helping you learn C# and .NET.  Smiley

    • yan

      Bob you look like Hollywood :)

    • BobTabor

      @yan: I've been doing this for 10+ years, however, that's the first time ever said that "I look Hollywood".  I'm assuming / hoping that's a good thing?  Wink

    • Zach Handzlik

      Great videos Bob! Quick question I try to run the application after the string message code, but the "You won a new car" doesn't pop up after the number is entered. There's a green squiggly line under message that says the variable message is assigned but the variable is never used. Any solutions to this?

    • Paige

      @Zach Handzlik -- Trying to help you out in case Bob is busy. Perhaps you didn't write: Console.WriteLine(message) at the bottom of your code? Perhaps you just have: Console.WriteLine()

    • BobTabor

      @Zach Handzlik: Just following up ... Did Paige's suggestion fix the issue?

      @Paige: Nice catch, and thank you!!!

    • RyanCox

      Great series.  Thanks, Bob!

    • hayyes

      Bob These series you've uploaded are very helpful as i am a beginner in C# and .NET.
      Frankly speaking i was unable to understand these concepts in my class but after watching ur videos you made it real easy. and INTERESTING........

    • Bri

      There's a problem in new C# express 2012. Compiler do not accept second "else if" after i remove {} from code.
      else if (userValue == "3") is also underlined with red wave line - "error CS1519: Invalid token 'else' in class, struct, or interface member declaration".
      13 minute, 29 line of code on video.

    • Sonia

      Thank you Bob : You are good! :)

    • BobTabor

      @Bri: I would make sure that the lines above the else statement are syntactically correct.  I assure you, nothing changed in the latest version of C#.  Hope that helps!

    • raul nguyen

      thank you so much Bob! I love yr videos. you are a great teacher.

    • hardik22

      Thank you very much Bob for these videos. I work in a Support Team and have keen interest in software development and just out of interest I developed two small applications for my team to automate some of their tasks.

      Your detailed explanation is helping me "Refactor" my poorly written code. I will complete the whole series and learn more Smiley You truly are a great Teacher. Thanks.






    • Ryan

      This is an excellent series. I know a bit of vb.net but I'm already enjoying this far more. You don't find tutorials of this quality often. Keep it up!

    • vishal prajapati

      Commendable Videos ! Great job mate.

    • Ben L

      I've been scripting for 10+ years and finally took the dive in to learning actual programming. I've tried learning C++ on my own with a c++ 'bible' and I became blocked and frustrated a few chapters in. Now, a few years later my passion for learning and creating is greater than ever. I've spent a while trying to decide on a language to learn and ultimately picked C# because it can be used in the Unity game engine and I've been wanting to create a 2d sprite game since junior high school.

      I wanted to let you know that your tutorials are very well edited, you have this very welcoming nature and presentation, and they are super approachable. You're a great teacher and the world could use more people with your passion to continue learning and sharing.

      (Keep the beard off, Steve Martin rules and you may get special treatment when going out!) :p

    • Mehul Shah

      Hi Bob,

      I have one doubt - why do we need to use "Console.ReadLine()" even when we actually dont want to read anything ? for example - the HelloWorld program, the if statements - all end with the ReadLine command. I tried personally and observed that the output window shows up and vanishes immediately if I do not use the ReadLine command? Is that the reason we use the ReadLine() command?

    • Supensaa

      Thank you! I highly appreciate these videos! Just saying this doesn't do enough justice to the feeling of gratitude I have for your work  Big Smile !

    • Luke

      @Mehul Shah - I believe it tells the console to wait for the user to give input for its use. Since the user has to enter information the console window never closes until enter is pressed.

    • SenCan

      I've been struggling with trying to make it continuous questioning after entering first number. OK I entered 1 and did not win the boat how can you make the program not to end and ask me the question again?

    • SenCan

      Sorry bothering. This worked:

    • Kevin

      Dear Bob,

      Your teaching series is awesome and have had no problems till now. The code you were writing in lesson 6 gives me a problem. The word "else" gives me the error "Invalid expression term" and the word "if" gives me the error "; expected". I am running the 2012 Visual Express edition and the program and course is awesome.

    • Stefan

      Hi Bob,
      I have the exact same problem as @Kevin and @Bri.
      Running 2012 VS. "else" = invalid expression term, and the curly bracket just above "else" gives the following error: Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement. I've checked over and over to make sure my code is exactly the same as yours, but nothing!
      Just also want to say thank you so much for these video lessons, you're a fantastic teacher!

    • Stefan

      Found my mistake! I had a Semi-colon after the: if (userValue == "1").

    • Lance Steel

      Like the others have stated you are a great teacher.

      The series needs to be updated though as I too cannot get the term "else" to function.

      Good luck!

    • Matt


      I'm learning C# and currently watching some excellent tutorial videos :-

      Channel 9 c# tutorial 6

      At 14:28 Bob talks about a condensed, easier way to write an if statement :-

      string message = (uservalue ="1") ? "boat" : "strand of lint";

      Just wondering if this is known as Pattern Matching which just checks for two conditions. Does anyone know if there is a way of writing a condensed if statement that checks for three conditions or more. Bob explains that this can be done by using a Switch statement. I know that c# is evolving all the time if anyone know a way please. Then it will help me keep my c# code more condensed.



    • Maurice

      These videos are so well done I wish more beginners to programming could find it. It took me awhile to find this location. Very impressive Bob, your diction is clear and your intonation brings home the concepts. Thanks a billion.

    • Dawn Ross

      Excellent presentation of these concepts. Over 30 as a Mainframe programmer and now needing to learn something new at this late stage of my career. I get it and eagerly awaiting my next Project to apply what I've learned.

    • Ferran

      you are simply amazing ! thanks for help us so much!

    • Tay

      Coming from programming in LabVIEW for several years. Finest teaching of the subject I've found, after browsing several books and online tutorials. Good Job!

    • An00bis

      Thanks you so much for your contribution to the free learning world. It is great to see some very high quality professional videos that are easy to follow. Also very pleasing that such a high profile company like Microsoft provide this for the community. Thanks Team  Big Smile

    • studyallthe​time

      This was a great help I am sure I will contue to use them to clarify and understand my errors as well Thank you

    • Jonatan

      Console.WriteLine("Would you prefer what is behind door number 1, 2 or 3?");
      string userValue = Console.ReadLine();
      if (userValue == '1')
      Console.WriteLine("You won a new car!");

      Error 1:
      Operator '==' cannot be applied to operands of type 'string' and 'char'

      I've checked it ten times, and i can't find any problems with it.
      I've tried with "int" (insted of string) and "ReadKey", and i still get the error?
      Any help please?

    • NewLearner

      Hi Bob,

      Thanks for your videos, they are so easy to follow along and work with. I have one question about this tutorial, you wrote the statement

      message = "you won a new car";

      in-between the if and else-if statements without writing console.WriteLine, how did the computer know to write the message string after each input?

      I would appreciate a response from anyone regarding this, really enjoying these videos, see you in the next one!

    • NewLearner

      HA! just looked back up the video and answered my own question. Thanks for the fantastic work :)

    • Matt Finch

      My first foray into the world of C# and what a truly EXCELLENT series to follow. Will be moving on to Lesson 7 tomorrow. The first 6 have me eager for more and it's only been my first evening. Great stuff Bob - so fluently and carefully explained too. :)

    • Hugo

      Thanks for the videos... did my C# course last week and i couldn't remember everything! this will help so much!

    • Mira

      Bob, thank you for the nice video lessons. My question is if there would be any difference to write
      insead of
      else if
      else if...

    • Mukesh

      Thanku so much Bob, because of u only I am willing to learn C#...Its really very helpful....As I have done MCA I am very weak in programming..but because of u i am feeling very comfortable....You are the best teacher i ever had..Hats Off...God bless you...

    • meir

      hi bob
      thank you very much for these very clear and helpful videos.
      when you write console.writeline("please type something")
      the .readline is telling he computer to present this string in the console untile canceled, right? and if instead of console.readline we type string uservalue =console.readline() the variable uservalue is set to the input entered by the user in the console, right? I am not sure I understand how in the second case the computer knows to apply the console.readline to user input as opposed to the "please type something in" in the first case. ??????

    • Peter G

      Hi my name is Peter and I'm 12 years old. I have recently become interested in C# and your videos are really helping me! Thank you and Great Job!

    • Pascal B

      Sorry but the last Version doesnt work for me. Is it possible that it wouldn´t work with the latest Visual Studio Ultimate 2013 Preview?

      My Version seems like this:

      string message = (userValue == "1") ? "Boat" : "Sorry i cant understand";
      Console.WriteLine("Da ist {0} you typed {1}", message, userValue);


    • Joss

      I'm really enjoying this series of videos, having coded in Perl and PHP to a basic level before, it's good to get down to something new.

      My one gripe is that the video is very blocky (using IE11 desktop version in Windows 8 Pro), yet it appears clear as crystal in Chrome. Someone might want to figure out why it is presented more clearly on a rival browser than Microsoft's own...

    • Joss

      Figured it out....if you change the format and force it to use Silverlight (from the option on the bottom right, underneath the video), it then appears just fine.

    • Clint

      @Joss: Chrome will do a straight MP4 download, if you have Silverlight, Channel 9 defaults to that and does an adaptive file download versus progressive.

    • Clint

      @Pascal B: did you do the line I bolded?  I tested out below and it ran in vs 2103 just fine.

      string userValue = Console.ReadLine();

      string message = (userValue == "1") ? "Boat" : "Sorry i cant understand";
      Console.WriteLine("Da ist {0} you typed {1}", message, userValue);

    • Clint

      @meir: readline will read whatever someone types until they hit enter, hence readline. 

      The first time you do string userValue = Console.ReadLine(); you are actually setting the line from the console to the string userValue.  The second Console.ReadLine(); at the end of the application is there just so you can see the output of the application.  When you hit enter, the application continues and because nothing is left to do work, it terminates.

    • satnam23

      hello Sir, thakn you sooo much this really great work. well done (y) ...
      Can you put some more videos for windows application in visual studio.

    • Clint

      @satnam23: Hey, we have a bunch more, Windows Store applications in VB, C#, and JavaScript/HTML5 along with Windows Phone 8!  http://channel9.msdn.com/posts/Beginner is where we keep an up-to-date list of our beginner series.

    • PtldTopher

      @Cale Elliott: I agree completely.  When I started programming we used interpreted BASIC and were still using punchcards to input some of our code.  Object Oriented concepts were difficult for me to gasp but this series of videos has made them almost trivial.  Thank you @BobTabor for making C# so easy.

    • ibrahim

      woooow AWESOME series Thanks a lot

    • Gary

      Please tell me what I'm doing wrong.
      string userValue = Console.ReadLine();
      string message = (userValue == "1") ? "boat" : "strand of lint";
      Console.WriteLine("You won a {0}! You typed {1}", message, userValue);



    • Clint
      @Gary: can you explain what is causing you to think it isn't? Looking at that, it seems correct.
    • ggrimes2013


      Thanks for the quick feedback. Yesterday I left my question under the name Gary.  Today I had to create a profile.

      I learned a big lesson yesterday: If you're tired put it down and get some rest.  After your assurance that the code was written correctly I found that the first write line was commented out... in just a few minutes this morning.

      Sorry to bother you.

      Thanks again for your help!


    • ggrimes2013


      I concur with the masses: you are a great instructor!

      I'm extremely new to programming and you have made it possible (through your mad teaching skills) for me to learn C# through self study.  I plan to get a lifetime subscription to your website after I complete this Channel9 course.

      I'm 52 and I wondered why it took me so long to get into this field.  That is until you reminded me of writing code in a text editor.  I dreaded logging on to a computer in the 80's and I can not imagine programming for a living then. Hats off to those that did.

      Many thanks!



    • Clint

      @ggrimes2013: glad you fixed it!

    • T2Tom

      Hi Bob,

      Thank you very much for this series. This has been very helpful for me to get started in C#.

      May I humbly point out for the sake of completion that you may nest conditional statements so that you can in fact be checking multiple conditions.

      For example to find the maximum of x, y, z you could use this line.
      string greatest = (x > y) ? (x > z) ? "x" : "z" : (y > z) ? "y" : "z";
      OK, I know that is probably not the most readable code, but I just like that it can be done concisely like this. ;)

      Again, thank you very much for your videos. Really appreciate your time and effort in making this series.

    • Clint

      @T2Tom: Tom, ternary operators are good for quick setting but as soon as you get into more complex logic, it becomes hard to maintain / read.  Think about a year down the line and you have to revisit that code, you'd have to read that code and grok what is happening rather than a quick glance.  Or when someone else has to look at that code.  Or what happens when new stuff has to be added to that if statement.  Having to refactor that could introduce bugs later since the existing logic may get misinterpreted.

      Remember the compiler is pretty smart and optimizes stuff.  I cannot stress readability enough in source code

    • Michael Vansuyt

      'ConsoleApplication1.vshost.exe' (CLR v4.0.30319: ConsoleApplication1.vshost.exe): Loaded 'C:\Windows\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
      'ConsoleApplication1.vshost.exe' (CLR v4.0.30319: ConsoleApplication1.vshost.exe): Loaded 'C:\Windows\assembly\GAC_MSIL\Microsoft.VisualStudio.HostingProcess.Utilities\\Microsoft.VisualStudio.HostingProcess.Utilities.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.

      The thread 0x6c0 has exited with code 259 (0x103).
      The thread 0x1684 has exited with code 259 (0x103).
      The thread 0xce4 has exited with code 259 (0x103).

      Output in the debugger????

    • Jack

      Hi Tom,

      Just wanted to say thanks for the videos. I do a lot of custom Excel spreadsheets and quite a bit of VBA programming (and make some decent compensation for it!), and used to write some VB code (6, not .NET). The corporate reporting stuff gets a little tedious though, and I'm interested in learning something different. I've been following along in the series, and this is the first one where my ears perked up at what you were demonstrating.

      Coming from a VB background, the syntax differences are interesting. I noticed the declaration of your variable in the body of the code, whereas traditional VB normally declares all variables at the top, before code execution starts. I assume that's standard accepted practice in C#?

      Also, the need (or not, depending on one or multiple lines) for curly braces inside the If/Else If statements. And the apparent lack of need for an End If statement at the conclusion of the If/Else If statements. In some ways, C# seems a little more efficient than VB, but in some ways a little more involved. I haven't gotten to the object-oriented programming aspect of it though, so the required syntax may have something to do with that.

    • Jack

      Sorry Bob. I meant Bob, not Tom. :-) Got too caught up in reading the earlier threads here!

    • Clint

      @Jack: declare as needed.  if you don't need a variable to be scoped to the class / application, why do it?  Also reduces the amount of scrolling you need to do Smiley

    • JEL

      In running through this code, how would I go about it so the console window does not close after an entry. So I could cycle through each question until I either entered all the options or guessed the correct one? What line would need to be added to the code for this? Thank you.

    • lindelbiz

      These are really great videos. Easier to learn than most in class tutors and lecturers. Thanks in a million

    • Sarath

      Bob , Thank you very much for this excellent video series for a total beginners. I appreciate you for taking time to make these videos. Very helpful.

    • Amica

      Console.WriteLine("Enter Your Name And Press ENTER!");
      string userName;
      userName = Console.ReadLine();
      Console.WriteLine("Thank you so much for teaching me this " + userName);

      That is all i have to say bob >.<

    • Niki

      Thank you for making it look so easy to learn c# for the absolute beginners!

    • John

      watched from the beginning all the way up to this video today. thanks for the wonderful explanations. there's really something comforting about your style, though perhaps part of it is that you really do look like Steve Martin

    • my opinion

      for me to understand I had to tweak your code as follows
      Console.WriteLine("Vyberte jednu z následujících možností 1,2 nebo 3");
      string userValue = Console.ReadLine();
      if (userValue == "1")
      Console.WriteLine("vybral jste moznost 1");

      else if (userValue == "2")
      Console.WriteLine("vybral jste moznost 2");
      else if (userValue == "3")
      Console.WriteLine("vybral jste moznost 3");
      Console.WriteLine("Neplatne zadani");

    • Caleb

      I followed EVERY step he showed on the screen, and when I debug the application, type '3' and press enter, I get the message "You won a <0>! And you typed typed <1>.. I followed EVERY EXACT step.

    Comments closed

    Comments have been closed since this content was published more than 30 days ago, but if you'd like to continue the conversation, please create a new thread in our Forums, or Contact Us and let us know.