Is there something like Or-Equals from Ruby to .NET / C #?

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

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

Ruby-ish purpose (two examples):

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

      

or

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

      

+1


source to share


3 answers


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

      



+10


source


You can 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.

+2


source


I think you are looking for something similar to SQL COALESCE or ISNULL. Here's a 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)

      

0


source







All Articles