Topics like health, travel, finance, home, living, education and careers | Media Search Home

Debug example: fix C# if statements in Visual Studio

When we write complex if statements, odds are we make an error sometimes. When that happens, we can look through the code in search for the mistake. Or we use Visual Studio"s debugging features. Let"s see how those features help with debugging if statements.

IN THIS ARTICLE:

  • Debug faulty C# if statements in Visual Studio
  • C# example application to debug in Visual Studio
  • Breakpoints to pause the C# program under the debugger
  • Start debugging C# code in Visual Studio
  • Fix the C# if error with Visual Studio"s debugging
  • Stop debugging C# code in Visual Studio
  • Summary
# Debug faulty C# if statements in Visual Studio

When we write if statements in our C# application, sooner or later we run into code that doesn"t behave right. Perhaps our nested if/else statement never runs or a cascaded if statement always executes the same code block. Either way, we"ll have to analyse our code and fix the problem.

Debugging is the process in which we identify and remove errors from our application (Asad & Ali, 2017). We can do that by looking through the code in search for the error. But a more efficient and scalable approach is to use special debugging tools.

One helpful debugging instrument is to step through our code. This executes our program line by line and shows how it behaves with each step (Asad & Ali, 2017; Dorman, 2010). Such a level of detail makes it clear why a particular if statement runs or why another fails to do so.

# C# example application to debug in Visual Studio

To see how we go about debugging C#‘s if statements, let"s explore a console application that has an error in it. After looking at the code we"ll explore which Visual Studio tools we can use in search for the bug.

The example console application helps a publisher find its next promising author. It has the following code:

using System; class Kodify_Example { static void Main(string[] args) { string authorName = "John Smith"; int booksWritten = 2; double royaltyAmount = 0.15; bool underContract = false; if (!underContract) { if (booksWritten > 1 && royaltyAmount >= 15) { Console.WriteLine("Seems to have potential. Let's reach out to {0}", authorName); } } } }

We begin the Main() method with declaring and initialising some variables. Then we come across an if statement:

if (!underContract) { if (booksWritten > 1 && royaltyAmount >= 15) { Console.WriteLine("Seems to have potential. Let's reach out to {0}", authorName); } }

Here we use first use the logical NOT operator (!) to check whether the underContract variable is false. When it"s true that underContract is false, the nested if statement executes.

That if statement has a condition that consists out of two logical expressions. The first is whether the author has written more than one book (booksWritten > 1). The other checks whether his or her royalty amount is greater than or equal to 15% (royaltyAmount >= 15). This way our publisher hopes to find highly qualified authors that have proven their worth to other publishers.

Since we combine both logical expressions with the logical AND operator (&&), both need to be true before the entire condition is true as well (Sharp, 2013). Should one or both be false, then this if statement"s condition is false as well – and its code will not run then.

Now say we expect the Console.WriteLine() method inside the nested if statement to run. But when we execute the program, nothing happens. But even though that means there"s an error somewhere, our program doesn"t trigger an error message. Often programming errors are small, subtle mistakes that don"t thrown big errors when the program runs. That makes them hard to find, and keep them unnoticed for a long time. Let"s see how we can use Visual Studio"s debugging tools to find the mistake.

# Breakpoints to pause the C# program under the debugger

To explore our program and see what values the variables and expressions have, it would be ideal if we could pause our program just before the nested if statement executes. Luckily we can with Visual Studio"s breakpoints.

With a breakpoint we mark a line of code where we want the program to pause (Price, 2017). Then each time the debugger executes our program and reaches the breakpoint, it pauses just before it runs the line with a breakpoint on it (Dorman, 2010; Liberty & MacDonald, 2009). This way breakpoints are our way of telling the debugger: ‘pause before this line executes so I can inspect the program’.

Without something like a breakpoint, our program simply runs under the debugger till completion. That wouldn"t give us a chance to inspect the program at its intermediate steps. Now when the debugger pauses (also called ‘breaks’) our program, several helpful debugging tools become available. For instance, at that point we can use Visual Studio"s tooltips to inspect values, continue the program by stepping through code, and track how variables and expressions change in the ‘Watch’ window.

One way to place a breakpoint is with a left-click in the code editor"s left margin. That makes the line marked with the breakpoint appear in red and also place a red dot before the statement:

Placing a breakpoint on C# code in Visual StudioPlacing a breakpoint on C# code in Visual Studio# Start debugging C# code in Visual Studio

Now that we placed a breakpoint in our code, we need to start debugging in Visual Studio. That makes the debugger run our program and pause it whenever it comes across a breakpoint or unhandled exception.

We begin debugging with the ‘Start Debugging’ icon ( Start debugging iconStart debugging icon; F5) from the ‘Debug’ toolbar:

Start debugging C# code in Visual StudioStart debugging C# code in Visual Studio

Now just before the line with the breakpoint is about to execute, the debugger stops program execution (Liberty & MacDonald, 2009). Visual Studio then brings up the code editor and gives the breakpoint line a yellow highlight:

Pausing a C# application under the Visual Studio debuggerPausing a C# application under the Visual Studio debugger

Once our program pauses under the debugger we can use several Visual Studio tools to analyse it:

  • When we hover our mouse over an expression, a small tooltip window appears with that expression"s value. This way we quickly check what the current values are and whether they match our expected values.
  • With the ‘Step Into’ ( Step Into iconStep Into icon; F11) and ‘Step Over’ ( Step Over iconStep Over icon; F10) debugging commands we step through programming code. That makes our program run just one or a few lines at a time, which gives a close view of how the program behaves.
  • We can evaluate and even change variables with Visual Studio"s ‘QuickWatch’ window. Then when we step through code we can see how those changes affect our program.
  • And with Visual Studio"s ‘Watch’ window we track variables and expressions so we see them change as we go through programming code.

Now let"s use one of these Visual Studio debugging features to troubleshoot our example console application.

# Fix the C# if error with Visual Studio"s debugging

The console application we introduced earlier has a problem: its nested if statement doesn"t execute even though we think it should. One debugging tool that particularly helps in situations like this are Visual Studio"s tooltips.

When Visual Studio"s debugger pauses our program, we can hover our mouse over expressions and variables. When we do, a small tooltip window appears with the value of the code element (Price, 2017). Based on where we place the mouse, the tooltip shows us which value a variable has, what an expression evaluates to, or how a collection or object is structured (Dorman, 2010; Sharp, 2013). This way we quickly check whether the value that our code assumes is also the one that"s present.

Since our example console application didn"t execute its nested if statement, we know that either that statement or the if statement above it prevents the nested if statement from running. So when our program pauses under the debugger, let"s use the Visual Studio tooltips to inspect those code elements.

We check the condition of the nested if statement by placing the mouse pointer on the logical AND operator (&&) like so:

Exploring a C# condition with Visual StudioExploring a C# condition with Visual Studio

Here we see that our nested if statement"s condition evaluates to false. When we assumed that this condition would be true, it"s worth to check its individual expressions separately.

When we hover the mouse over booksWritten > 1 we see that this expression is true:

Evaluating an expression with Visual StudioEvaluating an expression with Visual Studio

Because this part of the condition is true, let"s verify the other expression:

Checking another expression with Visual StudioChecking another expression with Visual Studio

This logical expression evaluates to false: royaltyAmount is not greater than or equal to 15. But since we combined both expressions with the logical AND operator (&&), both need to be true before the entire condition is true as well (Sharp, 2013). Since that isn"t the case, the nested if statement"s condition is false and its code never executes.

Let"s move the mouse over the royaltyAmount variable to see its current value:

Lookup the value of a variable with Visual StudioLookup the value of a variable with Visual Studio

Problem found! The royaltyAmount variable only has a value of 0.15, not 15. This makes the nested if statement condition false, which in turn prevents it from running its code.

The question that remains is whether this difference in values is by design or a bug. When we realise that royaltyAmount expresses a percentage, it looks to be an error: the nested if statement expressed a percentage as an integer while the royaltyAmount variable uses a decimal value. Once we fix this discrepancy and use a consistent scale, the nested if statement will have no trouble to execute its code when it"s supposed to.

# Stop debugging C# code in Visual Studio

Now that we found our error, we stop debugging. For that we use the ‘Stop Debugging’ icon ( Stop debugging iconStop debugging icon) from the ‘Debug’ toolbar (or press Shift + F5):

Stop debugging C# code in Visual StudioStop debugging C# code in Visual Studio

After we stop debugging, Visual Studio returns us back to the code editor where we make the necessary code adjustments based on what we learned while debugging. Then we remove the breakpoint. For that we click on the red dot in the code editor"s margin, or press F9 while the text cursor is on the code line with the breakpoint.

# Summary

To troubleshoot our if statement code we can search the code for errors. But that"s time consuming and doesn"t allow for easy experimentation. A better option are Visual Studio"s debugging tools. With those we can closely inspect a program while it runs. That way we can lookup values of expressions, change variables, and even execute the program one line at a time.

We start debugging with the ‘Start Debugging’ ( Start debugging iconStart debugging icon; F5) option. But before we do, we typically place a breakpoint to specify where the debugger should pause our program. Then every time when the debugger runs our program and reaches the breakpoint, it pauses just before executing that line. This way our program halts at areas where we want to take a close look.

Once our program pauses (also called ‘breaks’) under the debugger, several debugging tools become available. One feature is to step through code with just one or a few lines at a time. This way we see how running those lines affects the program. And with a debugging feature like the ‘Watch’ window we track variables and expressions and see how they change as we progress through the code.

When we troubleshoot if statements a particular helpful instrument are Visual Studio"s tooltips. When the debugger paused our program, those small windows appear when we hover the mouse over code elements. Those tooltips show the values of variables and expressions. This way we quickly check why an if statement"s code execute or why it failed to do so.

References

Asad, A. & Ali, H. (2017). The C# Programmer"s Study Guide (MCSD): Exam 70-483. New York, NY: Apress.

Dorman, S. (2010). Sams Teach Yourself Visual C# 2010 in 24 Hours. Indianapolis, IN: Sams/Pearson Education.

Liberty, J. & MacDonald, B. (2009). Learning C# 3.0: Master the Fundamentals of C# 3.0. Sebastopol, CA: O"Reilly Media.

Price, M.J. (2017). C# 7.1 and .NET Core 2.0 - Modern Cross-Platform Development: Create powerful applications with .NET Standard 2.0, ASP.NET Core 2.0, and Entity Framework Core 2.0, using Visual Studio 2017 or Visual Studio Code (3rd Edition). Birmingham, UK: Packt Publishing.

Sharp, J. (2013). Microsoft Visual C# 2013 Step by Step. Microsoft Press.

Last updated on October 25, 2018 (published February 24, 2018).
# Related C# tutorials
  • See C# code change while debugging with Visual Studio"s ‘Watch’

    Debugging C# code becomes easier with Visual Studio"s ‘Watch’ window, which shows values of expressions as we step through programming code.

  • Step through C# code: run a program line by line in Visual Studio

    In Visual Studio we can analyse our C# program line by line. This tutorial explores stepping through a C# application under the code debugger.

  • Quickly debug expressions with Visual Studio"s ‘QuickWatch’

    When debugging C# code, it often helps to quickly see what some expression evaluates to. The ‘QuickWatch’ window helps us do that and more.

  • Quickly check C# expressions with Visual Studio"s debugging tooltips

    When we debug C# code in Visual Studio, we often quickly want to see what an example evaluates to. For that we use Visual Studio"s tooltips.

  • Debug C# programming code with Visual Studio"s breakpoints

    Before we can debug C# code, our program has to pause under the debugger first. One way is to place a breakpoint on a line in Visual Studio.

« All C# visual studio articles


Email: contact@about.com.vn - Phone: 818.333.007 - Website: Media Search Home
Copyright © 2007 - Noos. All rights reserved