I recently started using enums for commonly used names in my application. The issue is that enums cannot be inherited. This is the intent:
public enum foreignCars
{
Mazda = 0,
Nissan = 1,
Peugot = 2
}
public enum allCars : foreignCars
{
BMW = 3,
VW = 4,
Audi = 5
}
Of course, this can't be done. In similar questions I found, people have suggested using classes for this instead, like:
public static class foreignCars
{
int Mazda = 0;
int Nissan = 1;
int Peugot = 2;
}
public static class allCars : foreignCars
{
int BMW = 3;
int VW = 4;
int Audi = 5;
}
But static classes can't be inherited either! So I would have to make them non-static and create objects just to be able to reference these names in my application, which defeats the whole purpose.
With that in mind, what is the best way to achieve what I want - having inheritable enum-like entities (so that I don't have to repeat car brands in both enums/classes/whatever), and without having to instantiate objects either? What is the proper approach here? This is the part that I couldn't find in any other questions, but if I missed something, please let me know.
EDIT: I would like to point out that I have reviewed similar questions asking about enum and static class inheritance, and I am fully aware that is not possible in C#. Therefore, I am looking for an alternative, which was not covered in these similar questions.
Enums in C# are a pretty weak implementation. They're basically just named values. Java's enums are a little nicer as they're actually classes with special semantics, so you could implement something similar to Java's enums...
Notice that the only instances of
Car
that can be created here are declared within the class itself, and no instances can be constructed externally because the constructor is private. This behaves much like an enum in Java, and allows you to include additional fields to the enum, rather than just name and value.One more thing to note here...
IsForeign
is declared as abool
. Foreign to you, might not be foreign to me, so consider globalization and localization too. Maybe you should specifyCar
byCountryOfManufacture
or better still, something from .NET's Culture namespace.If you're wondering where I got the inspiration for enum classes...Jimmy Bogard, the author of Automapper.
https://lostechies.com/jimmybogard/2008/08/12/enumeration-classes/