The reason your code does not compile as expected is that you have declared the enum Direction
to be a nested type, nested inside the outer type Form1
, while the referring type Palette
is not so nested. A nested type is a type defined within a class or struct. When referred to by code within that outer type, its name can be used directly. I.e. inside Form1
you can refer to your enum by simply doing Direction.Up
. But outside the containing type it is necessary to use the full name of the nested type, which is Form1.Direction
.
Thus, to fix your problem, you could:
-
Move
Direction
outside ofForm1
, making it a top-level type in theWindowsFormsApplication1
namespace.This is recommended if you are going to use
Palette
in multiple different forms. -
Make both
Palette
andDirection
be nested types insideForm1
.This is recommended if
Palette
is only used insideForm1
or needs access to access private or protected members ofForm1
. -
In
Palette
use the full name forDirection
:public Form1.Direction _direction { get; set; }
While this will compile it is not recommended as it is awkward and inconsistent.
Incidentally, you have an unrelated problem in your code, namely that your _direction
property has an infinite recursion. You should modify it to be an auto-implemented property or make the manually created backing field have a different name than the property.
Thus a fixed version of your code might look like:
public class Palette
{
Direction _direction;
public Direction Direction
{
set { this._direction = value; }
get { return this._direction; }
}
}
public enum Direction
{
Left, Right, Up, Down
}
public partial class Form1 : Form
{
private Palette p;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
p = new Palette { Direction = Direction.Up };
}
}
Since your full code apparently compiles, you may have some other type WindowsFormsApplication1.Direction
whose name would conflict with that of your nested Direction
type if you were to move it out of Form1
. If so, and you want to keep Palette
outside of Form
, your options are:
-
In the event they are actually duplicates, simply eliminate the inner nested type.
-
If they are not duplicates, rename the
Direction
enum to something else, sayDirectionType
.
11
solved Enumerated values compared to the left and right sides identified as inconsistent [closed]