I'm using C# in VS2005. I have a class library that contains several enums common to a number of different projects. When accessing one of these enums I have to specify the whole namespace path to the enum even though I have declared a 'using' directive to the namespace that contains the enum.
For example I have the following enum:
namespace Company.General.Project1
{
public static class Rainbow
{
[Flags]
public enum Colours
{
Red,
Blue,
Orange
}
}
}
Then in another project I have:
using Company.General.Project1;
namespace Company.SpecialProject.Processing
{
public class MixingPallette
{
int myValue = Company.General.Project1.Colours.Red;
}
}
Even though I have the 'Using' directive referencing the project that contains the class of the enum, I still have to write the enum longhand. Why can't I do the following...
using Company.General.Project1;
namespace Company.SpecialProject.Processing
{
public class MixingPallette
{
int myValue = Colours.Red;
}
}
Your enum isn't just in a namespace - it's a nested type. In fact, your sample "working" code wouldn't work, it would have to be
int myValue = (int) Company.General.Project1.Rainbow.Colours.Red;
(Not only do you need to include the Rainbow
part, but there's also no implicit conversion from an enum to int.)
Make your enum a top-level type:
namespace Company.General.Project1
{
[Flags]
public enum Colours
{
Red,
Blue,
Orange
}
}
Then you will be able to write:
using Company.General.Project1;
...
Colours x = Colours.Red;
int y = (int) Colours.Red;
(Note that to use [Flags]
effectively, you should be assigning values explicitly, e.g. 1, 2, 4, 8...)
EDIT: I've been assuming you really do want to be able to use Colours.Red
etc. You can keep your current structure, using a nested type, and just write:
Rainbow.Colours x = Rainbow.Colours.Red;
int y = (int) Rainbow.Colours.Red;
Unless you have a particular reason to make the enum nested, however, I wouldn't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With