Q: Better way to handle enum change methods? Initially, my hope was to have some sort of encapsulation with enums, but apparently that isn't yet possible with C#. My purpose was to store some sort of data with the enum. Ideally, having an enum of objects would have been great. But there's apparently no way to do that. So I created a state class, a public enum, and made a public getter/setter with a setter that initializes a method in which i can populate objects as a property.
I'm wondering if there's a slightly better way. The ideal solution for me would be to set a state (enum) the normal way:
car.State = CarStates.Idle;

and then access more data about that state like so:
string message = car.State.Message();

But this would involve attaching a property to the State enum. Is there any cool trick to achieve this effect? Are enums the only way you can make switchable, singleton-like values by simply adding .Idle to the end?
Here's the code as I have it now that keeps the state info at one level by adding a layer, which is passable, but feels redundant when declaring something like car.Mode.State = CarModeStates.Idle;.
class Car
{
    public CarState Mode;

    public Car()
    {
        Mode = new CarState();
    }
}

class CarState //holds any metadata for given enum value
{
    private int _EnumInt;
    private string _Message;
    private bool _IsError = false;

    public CarModeStates State
    { 
        get { return (CarModeStates)_EnumInt; } 
        set { _EnumInt = (int)value; InitializeState(value); } 
    }
    public string Message { get { return _Message; } }
    public bool IsError { get { return _IsError; } }

    public void InitializeState(CarModeStates? cs)
    {
        switch (cs)
        {
            case (CarModeStates.Off):
                {
                    _Message = "Car is off.";
                    _IsError = false;
                    break;
                }
            case (CarModeStates.Idle):
                {
                    _Message = "Car is idling.";
                    _IsError = false;
                    break;
                }
            case (CarModeStates.Drive):
                {
                    _Message = "Car is driving.";
                    _IsError = false;
                    break;
                }
            case (CarModeStates.Accident):
                {
                    _Message = "CRASH!";
                    _IsError = true;
                    break;
                }
        }
    }
}

public enum CarModeStates
{
    Off,
    Idle,
    Drive,
    Accident,
}

//And from the outside:
class SomeController
{
    Car car = new Car();
    public string GetStateMessage()
    {
        car.Mode.State = CarModeStates.Idle;

        return car.Mode.Message;
    }
}


A: Have you tried an extension method?  In a static class, define:
public static string Message( this CarStates value )
{
    switch (value) {
    ...
    }
}


A: Regular enums in C# are often not as problematic as your question suggests. Just make sure your switch statement has a default case that throws an ArgumentException to make sure you're getting one of the valid values. You have to be careful with the literal value 0 (which is implicitly convertible to any enum type), but other than that an enum in C# does offer substantial type safety at the API level.
C# enums perform substantially better than fully-encapsulated enums like Java uses. There are a few additional details to be aware of (e.g. values out of range), but they rarely cause problems in practice.

Java-style enum classes are easy to create in C#. Edit: except for the fact that you cannot use the switch statement on the C# version of an enum like this. 


*

*Make the class sealed.

*Make sure the class has at least 1 explicit constructor, and make sure all constructors are private.

*Translate members like the following:


Java:
enum Color { RED, GREEN, BLUE }

C#:
private class Color {
    public static readonly Color RED = new Color();
    public static readonly Color GREEN = new Color();
    public static readonly Color BLUE = new Color();

    private Color() { }
}

If you really want to mimic Java, you can get clever by creating an Enum<T> abstract base class for enums of this form that maintains an Ordinal property, and also create a static Values property like the following in the Color class:
public Color[] Values { get { return new[] { RED, GREEN, BLUE }; } }


A: An extension method combined with a dictionary might be a solution instead of a switch statement.
public static class CarExtensionMethods
{
    public static string Message(this CarStates value)
    {
        return carStateDictionary[value];
    }

    private static readonly Dictionary<CarStates, string> carStateDictionary;

    static CarExtensionMethods()
    {
        carStateDictionary = new Dictionary<CarStates, string>();

        carStateDictionary.Add(CarStates.Off, "Car is off.");
        carStateDictionary.Add(CarStates.Idle, "Car is idling.");
        carStateDictionary.Add(CarStates.Drive, "Car is driving.");
        carStateDictionary.Add(CarStates.Accident, "CRASH!");
    }
}

The usage is pretty straight forward:
CarStates state = CarState.Idle;
Console.WriteLine(state.Message());  //writes "Car is idling."

Also just as a side note, typically enum names should only plural when they have the [Flags] attribute.  The point is to indicate they can have more than one state.  A more stylistically appropriate name for your enum is CarState since it cannot have more than one state as a time.

A: If you are wanting to just use Enum values then you can create your own attributes to provide the extra meta data. 
The below example works but I personally would not model my domain this way.
// sample test app
class Program
{
    static void Main(string[] args)
    {
        var carState = CarModeStates.Accident;

        // the call to get the meta data could and probably should be stored in a local variable
        Console.WriteLine(carState.GetMetaData().Message);
        Console.WriteLine(carState.GetMetaData().IsError);
        Console.WriteLine(carState.GetMetaData().IsUsingPetrol);
        Console.Read();
    }
}

Extended enum example
// enum with meta data
public enum CarModeStates
{
    [CarStatus("Car is off."), IsError(false), IsUsingPetrol(false)]
    Off,

    [CarStatus("Car is idling."), IsError(false), IsUsingPetrol(true)]
    Idle,

    [CarStatus("Car is driving."), IsError(false), IsUsingPetrol(true)]
    Drive,

    [CarStatus("CRASH!"), IsError(true), IsUsingPetrol(false)]
    Accident
}

Custom attributes to decorate the enum
public interface IAttribute<out T>
{
    T Description { get; }
}

[AttributeUsage(AttributeTargets.Field)]
public class CarStatusAttribute : Attribute, IAttribute<string>
{
    private readonly string _value;

    public CarStatusAttribute(string value)
    {
        _value = value;
    }

    public string Description
    {
        get { return _value; }
    }
}

[AttributeUsage(AttributeTargets.Field)]
public class IsErrorAttribute : Attribute, IAttribute<bool>
{
    private readonly bool _value;

    public IsErrorAttribute(bool value)
    {
        _value = value;
    }

    public bool Description
    {
        get { return _value; }
    }
}

[AttributeUsage(AttributeTargets.Field)]
public class IsUsingPetrolAttribute : Attribute, IAttribute<bool>
{
    private readonly bool _value;

    public IsUsingPetrolAttribute(bool value)
    {
        _value = value;
    }

    public bool Description
    {
        get { return _value; }
    }
}

Extension method(s) to get the meta data about the enum.
public static class CarModeStatesExtensions
{
    public static CarModeStateModel GetMetaData(this CarModeStates value)
    {
        var model = new CarModeStateModel
            {
                Message = value.GetDescriptionFromEnumValue<string>(typeof (CarStatusAttribute)),
                IsError = value.GetDescriptionFromEnumValue<bool>(typeof(IsErrorAttribute)),
                IsUsingPetrol = value.GetDescriptionFromEnumValue<bool>(typeof (IsUsingPetrolAttribute))
            };

        return model;
    }
}

public class CarModeStateModel
{
    public string Message { get; set; }
    public bool IsError { get; set; }
    public bool IsUsingPetrol { get; set; }
}

public static class EnumExtensions
{
    public static T GetDescriptionFromEnumValue<T>(this CarModeStates value, Type attributeType)
    {
        var attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(attributeType, false).SingleOrDefault();

        if (attribute == null)
        {
            return default(T);
        }

        return ((IAttribute<T>)attribute).Description;
    }
}


A: Maybe you need a "factory" like that:
public class CarState
{
    private string message;
    private bool error;

    public CarState(string message, bool error)
    {
        this.message = message;
        this.error = error;
    }

    public string Message
    {
        get { return this.message; }
    }

    public bool Error
    { 
        get { return this.error; }
    }
}

public static class CarStateFactory
{
    public enum CarStateId { Off, Idle, Driving, Accident }

    public static CarState GetCarState(CarStateId carStateId)
    {
        switch(carStateId)
        {
            case (CarStateId.Off):
                { return new CarState("Car is off", false); }

            //add more cases

            default:
                return null;
        }
    }
}

With this you are able to set the state of your car by calling:
car.State = CarStateFactory.GetCarState(CarStateFactory.ID.Off); //ID.Idle, ID.Driving, ID.Accident

AND
You can access the message with car.State.Message.
EDIT:
Static getter for the CarStateFactory
public static CarState Idle
{
    get
    {
        return new CarState("Car is off", false);
    }
}


A: I know this is quite old but for further visitors, rather than using an enum for this, maybe use a state manager where an object represents each state?
Abstract
/// <summary>
/// Defines the expected members of a state
/// </summary>
internal interface ICarState
{
    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    string Message { get; }
}

The base state
/// <summary>
/// The class that all car states should inherit from.
/// </summary>
internal abstract class CarBaseState : ICarState
{
    #region ICarState Members

    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    /// </exception>
    public abstract string Message { get; }

    #endregion
}

Implementation
/// <summary>
/// Represents the state when the car is off
/// </summary>
internal class OffState : CarBaseState
{
    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    /// </exception>
    public override string Message { get { return "Off"; } }
}

/// <summary>
/// Represents the state when the car is idling
/// </summary>
internal class IdleState : CarBaseState
{
    /// <summary>
    /// Gets or sets the message.
    /// </summary>
    /// <value>
    /// The message.
    /// </value>
    /// </exception>
    public override string Message { get { return "Idling"; } }
}

Manager
internal class CarStateManager
{
    #region Fields

    Dictionary<string, ICarState> _stateStore = null;

    #endregion

    #region Properties

    /// <summary>
    /// Gets (or privately sets) the state of the current.
    /// </summary>
    /// <value>
    /// The state of the current.
    /// </value>
    internal ICarState CurrentState { get; private set;  }

    #endregion

    #region Constructors and Initialisation

    /// <summary>
    /// Initializes a new instance of the <see cref="StateManager"/> class.
    /// </summary>
    public CarStateManager()
    {
        _stateStore = new Dictionary<string, ICarState>();
    }

    #endregion

    #region Methods

    /// <summary>
    /// Adds a state.
    /// </summary>
    /// <param name="stateId">The state identifier.</param>
    /// <param name="state">The state.</param>
    public void AddState(string stateId, ICarState state)
    {
        // Add the state to the collection
        _stateStore.Add(stateId, state);
    }

    /// <summary>
    /// Changes the state.
    /// </summary>
    /// <param name="stateId">The state identifier.</param>
    public void ChangeState(string stateId)
    {

        // Set thr current state
        CurrentState = _stateStore[stateId];
    }

    #endregion
}

Program
class Program
{
    internal class StateKeys
    {
        public const string Off = "Off";
        public const string Idle = "Idle";
    }

    static void Main(string[] args)
    {
        // Instantiate the state manager
        CarStateManager stateManager = new CarStateManager();

        // Add the states
        stateManager.AddState(StateKeys.Off, new OffState());
        stateManager.AddState(StateKeys.Idle, new IdleState());

        // Change the state and display the message
        stateManager.ChangeState(StateKeys.Off);
        Console.WriteLine(stateManager.CurrentState.Message);

        // Change the state and display the message
        stateManager.ChangeState(StateKeys.Idle);
        Console.WriteLine(stateManager.CurrentState.Message);
        Console.ReadLine();
    }
}

Output:
Off
Idling

HTH!
