tags:

views:

118

answers:

3

I'm trying to do something in C# that I do all the time in Ruby, and I wondered what the closest thing would be.

If the Enum does not contain a definition for my integer value, I want it to default to a certain value. Can I do this in one line?

Ruby-ish assignment (two examples):

namedStr = Enum.GetName(typeof(myEnum), enumedInt) || "DEFAULT"

or

namedStr = Enum.GetName(typeof(myEnum), enumedInt)
namedStr ||= "DEFAULT"
+2  A: 

You could use:

namedStr = Enum.IsDefined(tyepof(MyEnum), enumedInt)
    ? ((MyEnum)enumedInt).ToString()
    : "DEFAULT";

...or:

namedStr = Enum.GetName(typeof(MyEnum), enumedInt) ?? "DEFAULT";

I like the second option better.

The ?? operator is known as the null coalescing operator.

Drew Noakes
+9  A: 
namedStr = Enum.GetName(typeof(myEnum), enumedInt) ?? "DEFAULT"
najmeddine
+1 beat me by a few seconds :(
Stan R.
Perfect, thank you.
cgyDeveloper
A: 

I think you're looking for something similar to SQL's COALESCE or ISNULL. Here's s snippet in VB:

Public Shared Function Coalesce(Of T)(ByVal value As T, ByVal NullValue As T) As T
    If value Is Nothing Then : Return NullValue
    Else : Return value
    End If
End Function

Used like:

myString = Coalesce(Of String)(x, valIfXIsNull)
Joey