0

First of all I am very sorry for the title, but its quite impossible (for me) to come up with a fitting title.

The problem is as follows, I have a Enum where a value is composed from flags of two values of the Enum:

[Flags]
Enum TknType : byte
{
   Number = 0x01,
   Constant = 0x02,
   Numeric = Number | Constant, // 0x03
   BinaryOpr = 0x04,
   UnaryOpr = 0x05,
   Function = 0x06
   //and so on an so forth
}

I want to check if a token is Numeric, but the token either is a Number or a Constant. How do I best do that?

I tired HasFlags() and Equals() in dotnetfiddle, but none of these work. HasFlags() returns only the first value Number. Here is the code I ran in dotnetfiddle:

var tt = TknType.Number;
var tt2 = TknType.Const;
if (tt == TknType.Numeric)
{
   Console.WriteLine("tt isnumeric equals");
}
if (tt2 == TknType.Numeric)
{
   Console.WriteLine("tt2 isnumeric equals");
}
if (TknType.Numeric.HasFlag(tt))
{
   Console.WriteLine("tt isnumeric has flag");
}
if (TknType.Number.HasFlag(tt2))
{
   Console.WriteLine("tt2 isnumeric has flag");
}

the output is "tt isnumeric has flag"

Where as I would like to have a condition that returns true for both Number and Const when checking against Numeric.

Prophet Lamb
  • 530
  • 3
  • 17

1 Answers1

1

I think you're looking for this:

var test = TknType.Numeric;

if ((test & TknType.Numeric) == TknType.Numeric) 
{
    Console.WriteLine("Test has Numeric flag");
} 
else if ((test & TknType.Number) == TknType.Number) 
{
    Console.WriteLine("Test has Number flag");
}
else if ((test & TknType.Constant) == TknType.Constant) 
{
    Console.WriteLine("Test has Constant flag");
}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Zohar Peled
  • 79,642
  • 10
  • 69
  • 121