C# How to use get, set and use enums in a class

I have a program where I use a class store settings. I need it to use set and get functions to change and store settings. I have tried this, and I don't get it to work. Can anyone help me with this one?

    private enum _Difficulty { Easy, Normal, Hard };

    public void SetDifficulty(Difficulty)
    {
        _Difficulty = Difficulty;
    }

    public enum GetDifficulty()
    {
        return _Difficulty;
    }

Is there no way to use enums in a class with get and set?

I also need this with bool and int.

Jon Skeet
people
quotationmark

There are several things wrong here:

  • Your enum is private, but your methods are public. Therefore you can't make your methods return type be the enum type, or have parameters with that type
  • Your SetDifficulty method has a parameter of just Difficulty - is that meant to be the parameter name or the type?
  • Your SetDifficulty method is trying to set the type rather than a field
  • Your GetDifficulty method is trying to use enum as a return type, and is then returning a type rather than a field

Basically, you seem to be confused about what your enum declaration is declaring - it's not declaring a field, it's declaring a type (and specifying what the named values of that type are).

I suspect you want:

// Try not to use nested types unless there's a clear benefit.
public enum Difficulty { Easy, Normal, Hard }

public class Foo
{
    // Declares a property of *type* Difficulty, and with a *name* of Difficulty
    public Difficulty Difficulty { get; set; }
}

You can use get/set methods if you really want to make your code look like Java instead of C#:

public enum Difficulty { Easy, Normal, Hard }

public class Foo
{
    private Difficulty difficulty;

    public void SetDifficulty(Difficulty value)
    {
        difficulty = value;
    }

    public Difficulty GetDifficulty()
    {
        return difficulty;
    }
}

people

See more on this question at Stackoverflow