Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
enum is a set of constants and cons variables hold values that wont changed, correct me if I'm wrong.thanks

What I have tried:

I'm studying basic c# and I read the definition of enum and constant variable but I would like to know if there is something else I should know
Posted
Updated 5-Jul-21 20:05pm

No, enum is a type that defines named values, a constant variable or value can be any type.

You use an enum variable to hold a value of the enum type, you use a const to define a variable that cannot change and whose value is known at compile time.

An enum variable can contain more than one "enum value":
C#
enum MyEnum
   {
   ValueA = 1,
   ValueB = 2,
   ValueC,
   ValueD
   }
...
MyEnum me = MyEnum.ValueA | MyEnum.ValueB;

And it can be const :
C#
enum MyEnum
   {
   ValueA = 1,
   ValueB = 2,
   ValueC,
   ValueD
   }
...
const MyEnum me = MyEnum.ValueA | MyEnum.ValueB;
 
Share this answer
 
v2
Yes, you can see similarities between the behavior of Enum and Const: both are immutable (unique, unchanging).

But, a Const is a simple Field that holds only certain basic Types: int, double, string. At compile time, any reference (use of its name/label) to the Const will be replaced by the value of the Const.

An Enum is a special Type (and a ValueType) of structure/class; like a Class, it can be defined in a NameSpace scope, or defined inside another Class. If you put it inside a Class, you will access it by: ClassName.EnumName ... the same way you would access any Class member defined as static,

I like to think of an Enum as an immutable Dictionary whose Key/Value pairs are Labels (strings) and ValueTypes (int, double, byte, etc.).

Enum also supports bitwise operations if it is adorned with the [Flags] attribute [^]
[Flags]
public enum FlagEnum
{
    caseNone = 0,
    case1 = 1, 
    case2 = 2, 
    case3 = 4,
    case1And2 = case1 | case2,
    case1And3 = case1 | case3,
    case2And3 = case2 | case3,
    caseAll = case1 | case2 | case3
}
With .NET FrameWork 4, the 'HasFlag method is available for an Enum with the [Flags] attribute: [^]. Note: using the None value in a bitwise and operation will always result in a value of #0.

Enum GetValues and GetNames methods allow access to the internal collections of labels and values in an Enum: I suggest you examine these when that kind of need arises.

There have been many criticisms of the implementations of HasFlag, GetValues, and GetNames. And, there are popular extensions available to handle their .. uhhh ... quirkiness. Just search on something like ... C# Enum GetValues alternative ...
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900