Jump to content
  • Advertisement
Sign in to follow this  
John H

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

This topic is 4481 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!