Reputation: 1042
namespace myobjects
{
class mylifeforms
{
public enum Animal { dog, cat, mouse }
}
}
if i want to use the the enum type in a class i need to declare the type like this:
myobjects.mylifeforms.Animal animal;
what should i do so i can declare it like:
Animal animal;
Upvotes: 0
Views: 173
Reputation: 46098
Within the mylifeforms
class you can reference the Animal
enum just by itself, but outside mylifeforms
you need to use mylifeforms.Animal
. It's specified in a roundabout way in sections 10.3.8.1 and 3.8 of the C# spec; the name resolution algorithm simply doesn't consider nested types when given a simple name.
You'll need to declare Animals
in the namespace rather than the class to refer to it using it's simple name everywhere
Upvotes: 2
Reputation: 185643
You'll have to create a manual type alias in your using
statements at the start of the file.
using Animal = MyObjects.MyLifeForms.Animal;
This is because you declared the enum
within the class rather than at the namespace level. If you were to do this:
namespace MyObjects
{
public class MyLifeForms
{
...
}
public enum Animal
{
...
}
}
It would be accessible as Animal
to any file that uses the MyObjects
namespace.
Upvotes: 1
Reputation: 63126
The reason for this is that you have placed the enum inside of the class.
if you defined the enum inside the namespace alone, it would not be needed.
So it would look like this.
namespace myobjects
{
class mylifeforms
{
}
public enum Animal { dog, cat, mouse }
}
Then you could use myobjects.Animal
to reference the enum. A simple using myobjects;
would then allow you to do it as Animal
.
Upvotes: 1
Reputation: 1042
Does it work if you declare the enum above the class , but within the namespace ?
Upvotes: 0
Reputation: 23462
Put the enum in the namspace instead of in the class. Than you can add the namepace with using
to get what you want.
namespace myobjects
{
public enum Animal { dog, cat, mouse }
class mylifeforms
{
}
}
Now if you add
using myobjects;
in the file where you want to use your enum you will get what you want.
Upvotes: 2