C#, ASP.Net, T-SQL & Azure – (With the odd indie game review!)

Bitwise Operators & Generic Methods in C#

A new communication framework we’re using at work has lead me to spend a long time focusing on using bitwise operators combined with enum flags.  Despite reminding me in a mind melting way of first year Computer Science Concepts, it did give me an opportunity to look into the representation and printing of Enumerations through the use of generic methods.

Lets say we have the below Enumeration Flag:

public enum MyCheckListOptions
    Apple = 1,
    Banana = 2,
    Pear = 4,
    Orange = 8

The representation of “Apple” would be “MyCheckListOptions myOption = MyCheckListOptions.Apple;” , or “1”

Whilst the representation of “Apple” or “Banana” would be “MyCheckListOptions myOptions = MyCheckListOptions.Apple | MyCheckListOptions.Banana;”  or “3” (1|2)

Now, something I learned last week was that if you cast an integer representation of the possible enumerations into the enumeration type, it will automatically assign the values as above, so:

int pearBananaApple = 7;

MyCheckListOptions myOptions = (MyCheckListOptions)pearBananaApple;

//”myOptions” Results in “MyCheckListOptions.Apple | MyCheckListOptions.Banana | MyCheckListOptions.Pear”

What’s even cooler is that you can then use string.Format to convert the above representation into a string, so if you want to show all the options to the user, the below code would accomplish that:

int pearBananaApple = 7;
MyCheckListOptions myOptions = (MyCheckListOptions)pearBananaApple;
lblMyLabel.Text = string.Format(“{0}”, myOptions).Replace(“0”, “None”);
//Sets the label text to “Apple, Banana, Pear”
//The replace is to set the text to “None” if no options are presented (Which comes out as “0”)

Now this is useful, however in the code I was creating I had to do the above conversion a number of times, so I started looking into generic methods.  These are powerful method types whereby you pass in the usual parameters along with a type; useful especially when using a series of similar classes that inherit the same interface.  The below method does exactly the same function as the above code, but for any enumeration flag with any bitwise value:

private string printBitwiseString<T>(int bitwiseValue) where T : struct
    return string.Format(“{0}”, (T)(ValueType)bitwiseValue).Replace(“0”, “None”);

To call it, you would use:

int pearBananaApple = 7;
lblMyLabel.Text = printBitwiseString<MyCheckListOptions>(pearBananaApple);

A brief explanation of the method; we have to declare the generic type as a “struct” to allow the explicit casting of the integer, otherwise the compiler will not allow it.  ValueType is similar to typeof() but allows us to use the generic type passed in

OK so this is all well and good, but how about a real world example? Lets face it, we’ll rarely be printing enumeration values to string, but we may often want to bind the enumerations to a check box list.  The below method is another example of a generic method, however this time doing something much more useful:

public class CheckboxBindDTO
    public string Value { get; set; }
    public string Text { get; set; }
    public bool Selected { get; set; }

. . . . . . . .

private void PopulateEnumCheckBoxes<T>(CheckBoxList cbxList, int bitwiseValue)
    var enumValues = Enum.GetValues(typeof(T)).Cast<Int32>().ToDictionary(=>Enum.GetName(typeof(T), x));
    IEnumerable<CheckboxBindDTO> enumValuesSelected = enumValues.Select
            new CheckboxBindDTO()
                Value = x.Value.ToString(),
                Text = x.Key,
                Selected = ((bitwiseValue & x.Value) != 0)
    cbxList.DataSource = enumValuesSelected;
    cbxList.DataTextField = “Text”;
    cbxList.DataValueField = “Value”;

    foreach (ListItem cbx in cbxList.Items)
        cbx.Selected = enumValuesSelected.Single(=> x.Text == cbx.Text).Selected;

To call this:

int pearBananaApple = 7;
PopulateEnumCheckBoxes<MyCheckListOptions>(cbxMyCheckBoxList, pearBananaApple);

An explanation of the code; the data transfer object is really just an extension of a dictionary with a boolean value for “Selected”.  The generic method populates an asp check box list with the string representations of the enumerations, however it also uses an integer passed in to determine which enumerations should be pre-selected.

After the binding, the for each loop then goes through each check box and sets it as “Selected” if the value matching it in the collection is represented in the bitwiseValue integer.  (This could be handled by the ASP by using an “<%eval..” statement, however I found issues doing this if the check box list is nested in another type of data bound list, so it’s safer to conduct it in code).

So, the result of this will look something like this:

Edit: Very good point from strider:

“FYI, if you specify None = 0 in your enumeration, you don’t have to call .Replace(“0″, “None”).”

About these ads

One response to “Bitwise Operators & Generic Methods in C#

  1. strider- May 6, 2011 at 7:28 am

    FYI, if you specify None = 0 in your enumeration, you don’t have to call .Replace(“0″, “None”).

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: