Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple ways to define C# Enums with [Flags] attribute?

Tags:

c#

.net

enums

flags

I understand how Enums work in C#, and I get what the Flags attribute brings to the table.

I saw this question, here. Which recommends the first flavor, but doesn't provide any reason/justification for it.

Is there a difference in the way in which these two are defined, is one better than the other? What are the advantages to using the first synax as instead of the second? I've always used the second flavor when defining Flags type Enums... have I been doing it wrong all this time?

[Serializable]
[Flags]
public enum SiteRoles
{
    User = 1 << 0,
    Admin = 1 << 1,
    Helpdesk = 1 << 2
}

Is that not the same as

[Serializable]
[Flags]
public enum SiteRoles
{
    User = 1,
    Admin = 2,
    Helpdesk = 4
}
like image 210
Nate Avatar asked Jan 25 '10 17:01

Nate


People also ask

How do you #define multiple variables in C?

Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

What are the different ways to define constant in C?

There are various types of constants in C. It has two major categories- primary and secondary constants. Character constants, real constants, and integer constants, etc., are types of primary constants. Structure, array, pointer, union, etc., are types of secondary constants.


1 Answers

The main advantage with the first one is that you don't need to calculate the correct values for each flag since the compiler will do it for you. Apart from that they are the same.

like image 163
Lee Avatar answered Sep 30 '22 12:09

Lee