I want to declare a nested enum like:
\\\\pseudocode
public enum Animal
{
dog = 0,
cat = 1
}
private enum dog
{
bulldog = 0,
greyhound = 1,
hus
public enum Animal
{
CAT_type1= AnimalGroup.CAT,
CAT_type2 = AnimalGroup.CAT,
DOG_type1 = AnimalGroup.DOG,
}
public enum AnimalGroup
{
CAT,
DOG
}
public static class AnimalExtensions
{
public static bool isGroup(this Animal animal,AnimalGroup groupNumber)
{
if ((AnimalGroup)animal == groupNumber)
return true;
return false;
}
}
See these questions:
Getting static field values of a type using reflection
Storing string values as constants in the same manner as Enum
The questions cover building a basic string enum, but I implement my answers using an ICustomEnum<T>
interface that might help you in this situation.
Perhaps this would suffice?
class A
{
public const int Foo = 0;
public const int Bar = 1;
}
class B : A
{
public const int Baz = 2;
}
This is my solution/work around:
public static class Categories
{
public const string Outlink = "Outlink";
public const string Login = "Login";
}
public enum Action
{
/// <summary>
/// Outlink is a anchor tag pointing to an external host
/// </summary>
[Action(Categories.Outlink, "Click")]
OutlinkClick,
[Action(Categories.Outlink, "ClickBlocked")]
OutlinkClickBlocked,
/// <summary>
/// User account events
/// </summary>
[Action(Categories.Login, "Succeeded")]
LoginSucceeded,
[Action(Categories.Login, "Failed")]
LoginFailed
}
public class ActionAttribute : Attribute
{
public string Category { get; private set; }
public string Action { get; private set; }
public ActionAttribute(string category, string action)
{
Category = category;
Action = action;
}
}
I would probably use a combination of enumerated bit fields and extension methods to achieve this. For example:
public enum Animal
{
None = 0x00000000,
AnimalTypeMask = 0xFFFF0000,
Dog = 0x00010000,
Cat = 0x00020000,
Alsation = Dog | 0x00000001,
Greyhound = Dog | 0x00000002,
Siamese = Cat | 0x00000001
}
public static class AnimalExtensions
{
public bool IsAKindOf(this Animal animal, Animal type)
{
return (((int)animal) & AnimalTypeMask) == (int)type);
}
}
Update
In .NET 4, you can use the Enum.HasFlag
method rather than roll your own extension.
I don't think it works that way.
Enumerations are supposed to be a simple set of parallel values.
You may want to express that relationship with inheritance.