Stackoverflow exception when using many enumarations inside my class

212 views Asked by At

I have some enum declarations that for unknown reason to me are causing StackOverflowException.

I have the following:

public enum PrimaryAttribute
{
    Strength,
    Agility,
    Intelligence
}

public enum Class
{
    Tank,
    Fighter,
    Sorcerer
}

public class Hero
{
    public PrimaryAttribute PrimaryAttribute { get; private set; }
    public Class Class 
    {
        get
        {
            return Class;
        }
        set
        {
            if (Class == Class.Tank)
            {
                PrimaryAttribute = PrimaryAttribute.Strength;
                IsBlocking = true;
            }
            else if (Class == Class.Fighter)
            {
                PrimaryAttribute = PrimaryAttribute.Agility;
                IsBlocking = false;
                IsDodging = true;
            }
            else if (Class == Class.Sorcerer)
            {
                PrimaryAttribute = PrimaryAttribute.Intelligence;
                IsBlocking = false;
                IsDodging = false;
            }
        }
    }
}

And in my main method I am calling this class and giving a value to Hero.Class

Hero hero = new Hero();
hero.Class = Class.Fighter;

At this point if I run it I get a StackOverflowException, why?

Basicly I just want to give values to some properties depending on the hero class..

1

There are 1 answers

1
David On BEST ANSWER

Enums won't cause a stack overflow. But this will:

get
{
    return Class;
}

Your getter for Class returns Class. Which is an infinite recursion.

You probably want to store the value in a backing variable:

private Class _class;
public Class Class
{
    get
    {
        return _class;
    }
    set
    {
        // your existing logic, but use the variable instead
    }
}