'StackOverflowException was unhandled' errors in C#

791 Views Asked by At

I have a problem with my code. I finally got it so there were no errors, but now i have to deal with stackoverflow...

can someone tell me what is wrong with my code?

    public Matrix Projection
    {
        get { return Projection; }
        protected set 
        {
            Projection = value;
            generateFrustum();
        }
    }

It would be nice if you could help!

thanks

4

There are 4 best solutions below

8
On

Your set method calls itself: Projection = value.

private Matrix _projection = null;
public Matrix Projection
{
    get { return _projection; }
    protected set 
    {
        _projection = value;
        generateFrustum();
    }
}

When you use following form:

public Matrix Projection { get; set }

you don't need to specify variable to store actual value, but when you implement get or set explicitly you should declare additional variable and use it in get, set implementations.

0
On

You are defining an infinite recursion on your get and set functions.

get { return Projection; }

is equivalent to:

get { return get();}.
0
On
public T PropA { get; set; } 

is actually syntax of

T _PropA; public T PropA { get { return _PropA; } set { _PropA = value; } }

So the answer will be

private Matrix _projection = null;
public Matrix Projection
{
    get { return _projection; }
    protected set 
    {
      _projection = value;
      generateFrustum();
    }
}

you can see read below examples for more info
http://msdn.microsoft.com/en-us/library/ms228503.aspx
http://msdn.microsoft.com/en-us/library/w86s7x04(v=vs.80).aspx

0
On

Properties' setters and getters are implemented as methods (get_X and set_X).

Writing Projection = value within the Projection's setter, causes a recursive call to set_Projection() from within set_Projection(). (The same applies to get_Projection().)

Since there is no condition surrounding the call, the recursion is infinite.

As for public T PropA { get; set; }, it is sugar syntax for:

private T _PropA;

public T PropA
{
    get
    {
        return _PropA;
    }
    set
    {
        _PropA = value;
    }
}

What you should do is:

private Matrix _projection;

public Matrix Projection
{
    get
    {
        return _projection;
    }
    protected set 
    {
        // Make sure that Matrix is a structure and not a class
        // override == and != operators in Matrix (and Equals and GetHashCode)
        // If Matrix has to be a class, use !_project.Equals(value) instead

        // Consider using an inaccurate compare here instead of == or Equals
        // so that calculation inaccuracies won't require recalculation

        if (_projection != value)
        {
            _projection = value;
            generateFrustum();
        }
    }
}