Sign in to follow this  
John H

[.net] [Solved] Testing for enum flags in a method

Recommended Posts

I've recently been reading a lot about Managed DirectX, and a lot of the methods seem to pass in enums, for which you can bitwise OR together many flags for single parameters (same thing in C++ obviously). It's peaked my interest a bit, so I looked into how I'd use a similar thing myself for C#. This is what I've got so far:
using System;

namespace MethodFlags
{
	class MethodFlagTest
	{
		[Flags]
		public enum OutFlags 
		{
			None = 0,
			One = 1,
			Two = 2,
			Four = 4,
		};

		static public void OutputFlags(OutFlags flags)
		{
			if (flags & OutFlags.None)
			{
				Console.WriteLine("No flags specified.");
				return;
			}
			if (flags & OutFlags.One)
				Console.Write("1 ");
			if (flags & OutFlags.Two)
				Console.Write("2 ");
			if (flags & OutFlags.Four)
				Console.Write("4 ");
		}

		[STAThread]
		static void Main(string[] args)
		{
			OutputFlags(OutFlags.Two | OutFlags.Four);
		}
	}
}



Just a simple test program. The problem is, for each of the if statements, I'm getting the following error: error CS0029: Cannot implicitly convert type 'MethodFlags.MethodFlagTest.OutFlags' to 'bool'. That makes sense except that if I try to cast the result to bool it gives me another error: error CS0030: Cannot convert type 'MethodFlags.MethodFlagTest.OutFlags' to 'bool'. I know it's something simple, but I can't seem to figure it out. Any hints would be wonderful. [wink] [Edited by - John H on April 15, 2006 9:08:27 PM]

Share this post


Link to post
Share on other sites
Change it to:


if ((flags & OutFlags.One) == OutFlags.One)
{
///
}



The bitwise and will return an enumeration type instead of a boolean.

Share this post


Link to post
Share on other sites
Edit: Nevermind again. Sorted it!


static public void OutputFlags(OutFlags flags)
{
if (flags == OutFlags.None)
{
Console.WriteLine("No flags specified.");
return;
}
if ((flags & OutFlags.One) == OutFlags.One)
Console.Write("1 ");
if ((flags & OutFlags.Two) == OutFlags.Two)
Console.Write("2 ");
if ((flags & OutFlags.Four) == OutFlags.Four)
Console.Write("4 ");
}



Thanks mate!

[Edited by - John H on April 15, 2006 9:38:21 PM]

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this