enumerations

  • Thread starter Thread starter C# beginner
  • Start date Start date
C

C# beginner

namespace mynamespace
{
internal enum ReturnCode
{
Fail = -1,
Success = 0,
...
}
}
If I have to use the enumeration from a class that is in
the same namespace, do I still have to type,
ReturnCode.Fail, ReturnCode.Success ...etc. Is there
anyway I can avoid typing the name of the enumeration?
Any feedback is appreciated.
 
C# beginner said:
namespace mynamespace
{
internal enum ReturnCode
{
Fail = -1,
Success = 0,
...
}
}
If I have to use the enumeration from a class that is in
the same namespace, do I still have to type,
ReturnCode.Fail, ReturnCode.Success ...etc. Is there
anyway I can avoid typing the name of the enumeration?
Any feedback is appreciated.

No - and that's a *good* thing, IMO, because it makes it explicit what
kind of enumeration you're talking about.

(Side note: rather than using return codes, most of the time you're
better off using exceptions to signal that a method has failed.)
 
No.

Enumerations are nothing more than classes (well structures) with constant
fields defined (that is basically how the CLR sees them). Consider the
following.

class OuterClass{
class InnerClass{
public void MyMethod();
}
}

If you wanted OuterClass to access MyMethod, you would have to explicitly
reference InnerClass.

The value of an enumeration does not belong to the class but rather to the
enumeration, which is its own entity.
 
The problem you have, is when two declarations of an enumeration have an
intersection in the set of named constants. As far as I am aware, you
cannot scope to the current enumeration. You cannot say, within the scope
of enumeration Day, do the following other statements, which could include
references to Mon, Tues, Wes, without the prefixed typename Day.
 
You have to write ReturnCode.Success/Fail, no way around it.

Rather than define a ReturnCode enum and pollute all your code with
ReturnCode.Success/Fail, you should consider two options:

* Returning a bool value (true/false)
* Not returning anything (void) and throwing exceptions when something goes
wrong.

Usually, the best approach is a mixture of the two above: you return a bool
value when the caller can do something about the failure case, and you throw
an exception when the event is really abnormal and the caller won't be able
to do anything about it (but somewhere higher in the call chain -- usually
an event loop or event handler --, there is a method that will catch the
exception, report it to the user and let the application go on).

Bruno.
 
Back
Top