I have been trying to debug the following code which was set out in a book:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HowToCreateUDTs
{
class Program
{
static void Main(string[] args)
{
Cycle degrees = new Cycle(0, 359);
for(int i = 0; i <= 8; i++)
{
degrees += 90;
Console.WriteLine("degrees = {0}", degrees);
}
}
}
struct Cycle
{
// private fields
int _val, _min, _max;
// constructor
public Cycle(int min, int max)
{
_val = min;
_min = min;
_max = max;
}
public int Value
{
get { return _val; }
set
{
if (value > _max)
this.Value = value - _max + _min - 1;
else
{
if (value < _max)
this.Value = _min - value + _max - 1;
else
_val = value;
}
}
}
public override string ToString()
{
return Value.ToString();
}
public int ToInteger()
{
return Value;
}
public static Cycle operator +(Cycle arg1, int arg2)
{
arg1.Value += arg2;
return arg1;
}
public static Cycle operator -(Cycle arg1, int arg2)
{
arg1.Value -= arg2;
return arg1;
}
}
}
At the first iterarion of the loop, the exception thrown is:
System.StackOverflowException was unhandled
and it occurs at the first addition operation.
Any help would be appreciated. It has me baffled.
DavePosted Jan 17, 2009, 8:55 PM
Hi Carl,
The algorithm is incorrect. I just checked the first edition of the book and he got it wrong in that edition as well (different error). It is meant to cycle around the degrees by 90. E.g. 90, 180, 270, 360. As you can see from the screenshot, it does not do that.
The book is the MCTS Self-Paced Training Kit (Exam 70-536) .NET Framework Application Development Foundation, Second Edition
How hopeless is that? The book we are meant to study to get MS certified cannot even get its code right. And it was not a tough algorithm either.
Carl SchraderPosted Jan 17, 2009, 11:10 AM
Dave,
If the output is incorrect then I am assuming your algorithm is incorrect. Can you please describe what you are trying to accomplish with your program (I may be able to help out)?
Carl
DavePosted Jan 16, 2009, 9:40 PM
correction is not that which is trying to be achieved - see screenshot
Me thinks an errata submissin is in order.
Carl SchraderPosted Jan 16, 2009, 9:13 PM
Dave, you are setting the Value property to itself (this.Value = ...) in the Value property setter which is causing the stack overflow.
Do the following instead:
public int Value
{
get { return _val; }
set
{
if (value > _max)
_val = value - _max + _min - 1;
else
{
if (value < _max)
_val = _min - value + _max - 1;
else
_val = value;
}
}
}
Carl