Sin Jeong-hun wrote:
On Jul 16, 9:09 am, Arne Vajhøj <a...@vajhoej.dkwrote:
>Sin Jeong-hun wrote:
>>This question may be stupid.
enum MyValues
{
Value1, Value2, Value3, Value4, Value5
}
...in the code...
MyValues test=MyValues.Value1 | MyValues.Value2;
...to check if it contains Value1 flag...
if( (test&MyValues.Value1) == MyValues.Value1) <== HERE
{
Do something.
}
I always did that way but is that the cleanest way? Is there more
shorter expression for that?
It is what MS prescribe:
http://msdn.microsoft.com/en-us/library/cc138362.aspx
I would probably have tested >0.
Thank you. I'd never looked that page before but if Microsoft have
explained that way, then maybe that's final. I just wondered if there
could be something like
if( test.Contains(MyValues.Value1) ) <== my imaginary Contains()
method
{
Do something
}
If on .NET 3.5 you could write an extension method.
Se below for inspiration.
Arne
=================================================
using System;
namespace E
{
public static class MyExtensions
{
public static bool Contains(this Enum o, Enum v)
{
return (Convert.ToInt32(o) & Convert.ToInt32(v)) 0;
}
}
[Flags]
public enum ABC { A, B, C };
public class Program
{
public static void Main(string[] args)
{
ABC o = ABC.A | ABC.C;
Console.WriteLine((o & ABC.A) 0);
Console.WriteLine((o & ABC.B) 0);
Console.WriteLine((o & ABC.C) 0);
Console.WriteLine(o.Contains(ABC.A));
Console.WriteLine(o.Contains(ABC.B));
Console.WriteLine(o.Contains(ABC.C));
Console.ReadKey();
}
}
}