"global" enums vs. enums in class?

H

Harold Hsu

Hi,

Originally, I have defined the following Enum within a namespace (outside a
class):

Public Enum UserRole
Admin
Manager
User
End Enum

And then later I learned that an Enum can be nested in a class. So I can
have:

Public Class User
Public Enum Role
Admin
Manager
User
End Enum
End Class

So instead of UserRole.Admin, I can say User.Role.Admin

My questions are:

1. Choosing one over the other is just a matter of preference?

2. If I access the named constant using User.Role.Admin, is the enum
treated like a static member?

Thanks,
Harold
 
J

Jay B. Harlow [MVP - Outlook]

Harold,
1. Choosing one over the other is just a matter of preference?
I see it more as a matter of Encapsulation, and less matter of preference.

If Role is specific to the User class than I would nest the Enum Role inside
of User as you did.

However if UserRole is independent of User, but still used by User (possibly
even only used by User currently), then I would not nest it and leave it as
UserRole as you did.

For the most part I only nest types inside another type when it is a private
implementation detail. I find Public types invariable feel better (to me)
when they are declared outside of another type.
2. If I access the named constant using User.Role.Admin, is the enum
treated like a static member?
No, it is treated the same as the UserRole enum, only the name is qualified.

Hope this helps
Jay
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top