I have the following class:
public class HandleResourceReferencesParams
{
public Factory Factory { get; set; }
public DataObject Resource { get; set; }
public HandleAction Action { get; set; }
public enum HandleAction
{
Activate,
Disable,
Terminate
}
}
Which is used in the following code:
var parameters = new HandleResourceReferencesParams();
parameters.Factory = context.Factory;
parameters.Resource = resource;
parameters.Action = parameters.HandleAction.Terminate; // Does not compile
HandleResourceReferences(parameters);
By using parameters.HandleAction
, I get a compile error:
Cannot access static enum 'HandleAction' in non-static context
The enum is clearly not declared 'static'. Why does it have a static context when it is referenced from an object instance (non static as well)?
EDIT: I already found the solution mentioned by Tim (Thanks by the way). I am just trying to understand why I am getting this error.
The error message is unfortunate, but it's not unfortunate that you can't do it... you're trying to access a member of a type, rather than a member of an instance of the type, but you're doing so "via" an instance.
Basically, it's the same reason that this code fails to compile:
Thread t = new Thread(...);
t.Start();
t.Sleep(1000); // Nope, Sleep is a static method
All nested types are effectively static members, in that you can't have a type which is specific to an instance of the containing type.
From the C# spec, section 10.3.7 (emphasis mine):
When a field, method, property, event, operator or constructor declaration includes a
static
modifier, it declares a static member. In addition, a constant or type declaration implicitly declares a static member.
So the enum is a static member of the type, despite not having the static
modifier.
See more on this question at Stackoverflow