How to deal with default case

  • Thread starter Thread starter codymanix
  • Start date Start date
C

codymanix

Say I have following method:


public string GetName(MyType type)
{
switch (type)
{
case MyType.Bananas:
return "Bananas";
break;
case MyType.Apples:
return "Apples";
break;
default:
// what now?
}
}

What is the best way to put into the default case? Debug.Assert(false) is
not sufficient, since the compiler complains about a missing return path. I
could also throw an ArgumentException or InvalidOperationException.
Or I could silenty return an empty string or null and doesn't bother the
user with an error message.

What is the best way, the best, the reccommended style?
 
Or you can just return a NULL and let the caller determine what to do about
that. However, since an enum has a finite number of elements, it is really
possible for this method to be called where you don't know all the possible
values?
 
codymanix said:
Say I have following method:


public string GetName(MyType type)
{
switch (type)
{
case MyType.Bananas:
return "Bananas";
break;
case MyType.Apples:
return "Apples";
break;
default:
// what now?
}
}

What is the best way to put into the default case? Debug.Assert(false) is
not sufficient, since the compiler complains about a missing return path. I
could also throw an ArgumentException or InvalidOperationException.
Or I could silenty return an empty string or null and doesn't bother the
user with an error message.

What is the best way, the best, the reccommended style?

I'd throw an ArgumentException, myself. Silently returning an empty
string or null is definitely a bad idea.
 
Peter Rilling said:
Or you can just return a NULL and let the caller determine what to do about
that.

Sounds like a bad idea to me - you may call the method from hundreds of
different places. Sticking tests on the return value of each of those
is much more costly in terms of maintenance than throwing an exception.

Of course, in some cases it's *not* a programming error to pass in a
value which isn't specifically within the enumeration, but I'm assuming
in this case it is.
However, since an enum has a finite number of elements, it is really
possible for this method to be called where you don't know all the possible
values?

Absolutely - you can cast from the "base type" of an enum to the enum
type, for instance.
 
I prefer an ArgumentOutOfRangeException to be thrown since the argument is
out of your methods supported range for this type .As an aside you could
just do type.ToString() which could give you "Bananas" or "Apples" anyway
(for an enum).

Regards
Lee.
 
Back
Top