views:

46

answers:

3

I need a NOT operation on Enumeration in VB.NET (.NET 2), is it possible?

  <DefaultValue(0)> _
  Public Enum Orientation
    Descending = -1
    Undefined = 0
    Ascending = 1
  End Enum

by ex define a Not operation in order to do

myObj1.Orientation = Not myObj2.Orientation

Rules:

Desceding > Ascending, 
Ascending > Desceding, 
Undefined > Undefined
A: 

In general you'll need to code up a specific method as only you know what's the inverse of each of your enumeration values is.

There might be easier approaches for simple enumerations, but if there's a complicated relationship between the values making it explicit is the only way to go.

(You'll have to forgive the C# style pseudo code.)

public Orientation invert(Orientation original)
{
    Orientation result;
    switch (original)
    {
        case Orientation.Descending:
            result = Orientation.Ascending;
            break;
        case Orientation.Ascending:
            result = Orientation.Descending;
            break;
        default:
            result = original;
            break;
    }
    return result;
}
ChrisF
`return -1 * original` seems to be enough :) thanks however!
serhio
@serhio - that would work in this case, but in the general case where the enum values aren't specified you'll have to do this.
ChrisF
+5  A: 

There is no general way to do this because enumerations are an integral type and Not on integral types does a bitwise operation which is not what you want here. However, in your case you can simply write a method that inverts the orientation:

Module OrientationExtensions

    <Extension()>
    Public Function Invert(ByVal orientation As Orientation) As Orientation
        Return -1 * orientation
    End Function

End Module

Usage:

Dim orientation As Orientation
orientation = Module1.Orientation.Ascending
orientation = orientation.Invert()
0xA3
can I attach this method to be the enumeration member?
serhio
@serhio: Yes, you can turn it into an extension method, see my updated answer. You can use this with .NET 2.0, but you will need to have the C# 3.0 compiler (i.e. Visual Studio 2008 or later). If you don't have that simple use the function like this: `orientation = Invert(orientation)`
0xA3
A: 

You can create an extension method:

Imports System.Runtime.CompilerServices

Module OrientationExtensions

  <Extension()>
  Public Function Invert(ByVal orientation As Orientation) As Orientation
    If orientation = Orientation.Ascending Then
      Return Orientation.Descending
    ElseIf orientation = Orientation.Descending Then
      Return Orientation.Ascending
    Else
      Return Orientation.Undefined
    End If
  End Function

End Module

Then you can use it like this:

Dim orientation As Orientation = Orientation.Ascending
Dim inverseOrientation As Orientation = orientation.Invert
Martin Liversage
note .NET version 2
serhio