Everything you ever wanted to know about an enum (well, almost everything)

The enum, what a lovely creature available to us in C#. They help make our code more readable and bug-resistant. They also have some tricks up their sleeves.

Take a sample enum declaration:

public enum Level
{
Unknown = 0,
Low,
Medium,
High
}

If you want a string representation of an enum, you simply use the ToString() method.

Console.WriteLine(Level.Unknown.ToString());
/* output:
Unknown
*/

If you want the numeric value of an enum, cast it to an int. (By default, an enum is an int, though you can specify other numeric values for them.)

int i = (int)Level.Low;
Console.WriteLine(i);
/* output:
1
*/

If you have a string and want to convert it to an enum, use the Enum.Parse() method. Pass the enum type, the string value to parse, and an optional boolean parameter to note if you want the parsing to be case-insensitive. (By default, parsing is case-sensitive.)

Level lvl;

// case-insensitive parsing
lvl = (Level)Enum.Parse(typeof(Level), "medium", true);
Console.WriteLine(i);
/* output:
Medium
*/

// default, case-sensitive parsing
lvl = (Level)Enum.Parse(typeof(Level), "high");
/* throws an exception:
System.ArgumentException: Requested value 'high' was not found.
*/

If you have a numeric value and want to . . .

→ Read More: Everything you ever wanted to know about an enum (well, almost everything)

C# 3.0′s syntatic sugar

In the old days, we’d write something like this:

view.Rows.Add("Type");
view.Rows.Add("Count");
view.Rows.Add("Whatever");

With C# 3.0 we can do this:

new string[] { "Type", "Count", "Whatever" }
.ForEach(str => view.Rows.Add(str));

That is very cool syntatic sugar. Sure, this is not new news, but when you think about C# in the context of the new features available in 3.0, it really starts to feel a lot more like coding with JavaScript (which is a . . .

→ Read More: C# 3.0′s syntatic sugar

Google AdSense ViewComponent for MonoRail

Like many, I use Google AdSense to host ads on my web sites. Including the ad code typically requires you to paste a block a block of JavaScript onto the page. I don’t mind injecting the JavaScript, but I wanted to come up with a better way.

The solution I came up with was a quick MonoRail ViewComponent, AdUnit. It has a simple purpose: to render a block of code for an ad unit of a given size.

The first task was to create an enum which represented all the possible ad unit sizes, based on what’s offered by Google. . . . → Read More: Google AdSense ViewComponent for MonoRail