C# How to use get, set and use enums in a class
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 justDifficulty
- 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 useenum
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;
}
}
You code tries to assign Difficulty
a value, when in fact Difficulty
is the name of the enum
type. I would encourage use of getters and setters as properties instead:
public enum Difficulty { Easy, Normal, Hard };
private Difficulty _difficulty;
public Difficulty CurrentDifficulty
{
get { return _difficulty; }
set { _difficulty = value; }
}
This way you can add additional code in the setter for special conditions. To use it you simply do the following:
//set
CurrentDifficulty = Difficulty.Easy;
//get
Difficulty theDifficulty = CurrentDifficulty;
Once you specify an enum using the enum
keyword, that enum acts as a type, like a class
or struct
would.
Here's how you'd implement a property with a custom enum:
public enum _Difficulty { Easy, Normal, Hard };
public _Difficulty Difficulty { get; set; }