简体   繁体   中英

C#/Visual Studio Debugging example

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!

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

string a = "foo";
a.Replace("foo", "bar");
Console.WriteLine(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.

Something like this:

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

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

if (a != b)
{
  Method1();
  Method2();
}

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);
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM