user3524922 - 1 year ago 63
C# Question

# C# Enums and possibly having a default value?

So I have the following enum and I need it to have a "None" item which is used by other code, like the method: GetCompassDirectionFromUnitVector as shown below:

``````    public enum CompassDirection
{
North = 90,
Northeast = 45,
East = 0,
Southeast = -45,
South = -90,
Southwest = -135,
West = 180,
Northwest = 135,
None = null
}

/// <summary>
/// Returns compass direction (North, Southwest, etc.) from a given direction unit vector.
/// Returns CompassDirection.None if given Vector is not a unit vector.
/// </summary>
/// <param name="vec">Direction unit vector</param>
/// <returns></returns>
public static CompassDirection GetCompassDirectionFromUnitVector(Vector vec)
{
Dictionary<Vector, CompassDirection> list = new Dictionary<Vector, CompassDirection>()
{
{new Vector(0, 0), CompassDirection.None},
{new Vector(0, 1), CompassDirection.North},
{new Vector(0, -1), CompassDirection.South},
{new Vector(1, 0), CompassDirection.East},
{new Vector(-1, 0), CompassDirection.West},
{new Vector(1, 1), CompassDirection.Northeast},
{new Vector(1, -1), CompassDirection.Southeast},
{new Vector(-1, 1), CompassDirection.Northwest},
{new Vector(-1, -1), CompassDirection.Southwest},
};
if (list.ContainsKey(vec))
{
return list[vec];
}
return CompassDirection.None;
}
``````

But I'm writing the following method:

``````   Angle GetAngleFromCompassDirection(CompassDirection dir)
``````

So having the angles in the enum values is incredibly useful here.
But integers aren't nullable so having that "None" value enum is invalid.

How do I go around this?

The default for an Enum value will always be Zero (0). What I would recommend is for you to change your implementation to:

``````public static CompassDirection? GetCompassDirectionFromUnitVector(Vector vec)
{
Dictionary<Vector, CompassDirection> list = new Dictionary<Vector, CompassDirection>()
{
{new Vector(0, 0), CompassDirection.None},
{new Vector(0, 1), CompassDirection.North},
{new Vector(0, -1), CompassDirection.South},
{new Vector(1, 0), CompassDirection.East},
{new Vector(-1, 0), CompassDirection.West},
{new Vector(1, 1), CompassDirection.Northeast},
{new Vector(1, -1), CompassDirection.Southeast},
{new Vector(-1, 1), CompassDirection.Northwest},
{new Vector(-1, -1), CompassDirection.Southwest},
};
if (list.ContainsKey(vec))
{
return list[vec];
}
return null;
}
``````

(Note the Nullable return Type) You can then treat null valus as you would otherwise treat CompassDirection.None.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download