Should I return an int or an enum?

  • Thread starter Thread starter thechaosengine
  • Start date Start date
T

thechaosengine

Hi all,

I have a property called GeneralStatus that can return an int between -1 and
3.

These values are represented by an enumeration called StatusEnum.

My question is, should my property definition return a int (the underlying
type of the enum) or should I return the enum itself.

What would returning the enum achieve?

Many thanks

tce
 
The only advantage is, you can easy readability of an enum. So, you can easy
check it for certain returns without knowing the int values.

myReturn == myEnum.Failed

However, using a enum won't guarantee you returning values outside of enum.
(for some reason c# does not provide this check)
 
thechaosengine said:
Hi all,

I have a property called GeneralStatus that can return an int between -1
and 3.

These values are represented by an enumeration called StatusEnum.

My question is, should my property definition return a int (the underlying
type of the enum) or should I return the enum itself.

What would returning the enum achieve?

Better type checking. The compiler will give you errors if you mess up and
assign or compare with a value that does not belong to the enum (a member of
another enum for example).
 
Bruno,

Actually C# does not do "bounds" checking on enums. Try this:

public enum MyEnum
{
first = 1,
second = 2
}

MyEnum x = (MyEnum) 100;

and the code works! If anything, the enums are best when you want to checks
against a known set of numeric values. Also, better readability.

--
Manohar Kamath
Editor, .netWire
www.dotnetwire.com
 
Manohar Kamath said:
Bruno,

Actually C# does not do "bounds" checking on enums. Try this:

public enum MyEnum
{
first = 1,
second = 2
}

MyEnum x = (MyEnum) 100;

and the code works! If anything, the enums are best when you want to
checks
against a known set of numeric values. Also, better readability.

I know, but typing is not (at least in C#) about bounds checking, it is
about distinguishing what needs to be distinguished, and about increasing
the amount of verifications performed by the compiler. For example, an API
like:
MyEnum MyFunc()
is different from an API like:
int MyFunc()
because it will get a compile time error if you write something like:
MyOtherEnum val = MyFunc();

Of course, if you start casting, you are on your own!

Bruno.
 
Back
Top