Enums and Arrays of Enums

J

J055

Hi

The function below accepts an Enum value 'AccountRoles' and should return an
array of Permissions which is also an Enum. When the AccountRoles is
AccountRoles.Administrator it should always return the full list of values
from the Permissions enum. Is there a clean way to do this?


public static Permissions[] GetPermissions(AccountRoles role)
{
switch (role)
{
case AccountRoles.Administrator:
return new Permissions[] { }; // need to return an array
of all Permissions enum values
case AccountRoles.Publisher:
return new Permissions[] {
Permissions.CreateAccount,
Permissions.DeleteAccount,
Permissions.EditAccount,
Permissions.ViewAccounts
};
}
}

Many thanks
Andrew
 
G

Greg Young

Probably the cleanest way would be to define your Permissions enum as a
flags (would also make alot more sense compared to what you are doing here).
You could then have a value for "all" as an example ...

[Flags]
public enum Permissions
{
CreateAccount = 1,
EditAccount = 2,
DeleteAccount = 4,
ViewAccounts = 8,
All = CreateAccount | EditAccount | DeleteAccount | ViewAccounts
}


You might also want to see
http://msdn2.microsoft.com/en-us/library/ms229062.aspx

The great thing here is it also prevents you from having to return an array
(the enum does it for you) ...

Permissions p = Permissions.CreateAccount | Pemissions.DeleteAccount;
Console.WriteLine(p);

Cheers,

Greg Young
MVP - C#
http://codebetter.com/blogs/gregyoung
 
N

Nicholas Paldino [.NET/C# MVP]

Andrew,

You can always do this:

switch (role)
{
case AccountRoles.Administrator:
return (Permissions[]) Enum.GetValues(typeof(Permissions));
..
..
..

Hope this helps.
 

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