Should I return an int or an enum?

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
 
M

Manohar Kamath

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)
 
B

Bruno Jouhier [MVP]

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).
 
M

Manohar Kamath

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
 
B

Bruno Jouhier [MVP]

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.
 

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