views:

459

answers:

4

Hi,

I am trying to work out a code sample to demonstrate the debugging functionality in Visual Studio 2008 with C#. I'm trying to build a code sample which would have a 'not so obvious' mistake in it, which would result in unexpected output.

A non working example would be:

static void Main(string[] args) {
    int a, b;

    a = args[0];
    b = args[1];

    if (a = b) Console.WriteLine("They are equal!");
    else if (a < b) Console.WriteLine("Number 1 is smaller!");
    else Console.WriteLine("Number 1 is larger!");
}

Something like this would not be too obvious when just reading over the code, but it could easily be detected with debugging.

I'm looking for such an example which would work in Visual Studio 2008 with C#.

Thanks for the help!

+4  A: 

Here's a snippet you can throw in...

string a = "foo";
a.Replace("foo", "bar");
Console.WriteLine(a);
Shawn Simon
A: 

You could use a common programming error like:

I think that a fencepost error might work best for a debugging example. The code could appear to run through a for-loop over an entire array/collection/whatever, but maybe it uses obj.length instead of obj.length-1.

EndangeredMassa
A: 

Something like this:

if (a != b)
  Method1();
  Method2(); // will always be called, even if a == b

...which happens if you omit the curly braces, e.g. the intention was this:

if (a != b)
{
  Method1();
  Method2();
}
M4N
For this mistake, the debugger is the wrong way to point out.
BeowulfOF
This error can be hard to see, if you just glance over some code (it happend to me). When stepping through that code in the debugger, the "error" will be clear instantly.
M4N
I agree, the debugger is great for this.
stimpy77
A: 

A few other simple mistakes which I have run into:

1 - Removing items from a collection while iterating over it with foreach (although this throws an exception so if uncaught then you'll probably notice it without needing a debugger):

foreach (LayoutVersion lv in this.LayoutVersions)
{
    if (lv.EndDate <= endDate && lv.StartDate >= endDate)
    { //subsume this lv
        this.LayoutVersions.Remove(lv);
    }
}

2 - DateTime.AddMinutes or AddHours without assigning the result:

 public Report Create(Area area, DateTime date, Shift shift)
    {
 DateTime startDate = new DateTime(date.Year, date.Month, date.Day);
 startDate.AddHours(shift.Time.Hour);
 startDate.AddMinutes(shift.Time.Minute);
 return Persistence.DataManager.CreateReport(area, startDate);
    }
Coxy