Debug example C # / Visual Studio

I am trying to develop a sample code to demonstrate the debugging functionality in Visual Studio 2008 using C #. I am trying to create sample code that will have a "not so obvious" error in it, resulting in unexpected output.

Non-working example:

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 won't be too obvious if you just read the code, but it can be easily spotted with debugging.

I'm looking for an example like this that will work in Visual Studio 2008 from C #.

Thanks for the help!

+1


source to share


4 answers


Here is a snippet you can add ...



string a = "foo";
a.Replace("foo", "bar");
Console.WriteLine(a);

      

+4


source


You can use a common programming error like:



I think the fencepost error might work best for the debug example. Perhaps the code runs through a for loop over the entire array / collection / whatever, but perhaps it uses obj.length instead of obj.length-1.

0


source


Something like that:

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

      

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

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

      

0


source


Several other simple errors that I ran into:

1 - Removing items from the collection while iterating over it with foreach (although this throws an exception, so if not photographed, you will probably notice it without debugging):

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

      

0


source







All Articles