Enum Parse Extension Methods

When I write code I don't like to depend on catching exceptions to control my programming logic, so as much as I can I try to check for nulls, empty, etc...

When parsing one type into another there are usually TryParse() methods available so that an exception does not occur. I've always been a little confused why there wasn't such a method off the Enum class. So, I decided to make my own.

However, after I started to extend the TryParse method off of the Enum, the answer started to become clear why that was not a feature :) I could extend the actual specific enum, but that didn't really help me any. I wanted a Generic solution for all enums.

So, instead of making an Enum.TryParse(), I decided to extend the string class to add string.ToEnum() and string.TryToEnum(). The string is usually the class that I want to parse into a specific Enum after all.

The following is the Extension methods that I created...


using System;

namespace Web.Helpers {
public static class EnumHelper {
public static bool TryToEnum(this string obj, out T parsed) {
bool isParsed = false;

if (Enum.IsDefined(typeof(T), obj)) {
parsed = (T)Enum.Parse(typeof(T), obj);
isParsed = true;
} else {
parsed = (T)Enum.Parse(typeof(T), Enum.GetNames(typeof(T))[0]);
}

return isParsed;
}

public static T ToEnum(this string obj) {
return (T)Enum.Parse(typeof(T), obj);
}
}
}
</pre>

I created a set of 4 MS Unit tests to exercise different scenarios that might exist. Let me know if you see any other tests that I should test.


using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Web.Helpers;

namespace WebTests.Generic {
[TestClass]
public class EnumTest {
public enum Color { Red, Orange, Yellow, Green, Blue, Indigo, Violet };

[TestMethod]
public void TryToEnumWorksWithValidEnum() {
Color parsedColor = Color.Blue;

string realColor = "Yellow";
bool canParse = realColor.TryToEnum(out parsedColor);
Assert.AreEqual(true, canParse);
}

[TestMethod]
public void TryToEnumWorksWithInvalidEnum() {
Color parsedColor = Color.Blue;

string fakeColor = "Elijahish";
bool canParse = fakeColor.TryToEnum(out parsedColor);
Assert.AreEqual(false, canParse);
}

[TestMethod]
public void ToEnumWorksWithValidEnum() {
Color parsedColor = Color.Blue;

string realColor = "Yellow";
parsedColor = realColor.ToEnum();
Assert.AreEqual(Color.Yellow, parsedColor);
}

[TestMethod, ExpectedException(typeof(ArgumentException), "Unable to parse enum")]
public void ToEnumThrowsExceptionWithInalidEnum() {
Color parsedColor = Color.Blue;

string fakeColor = "Elijahish";
parsedColor = fakeColor.ToEnum();
}
}
}
</pre>

Have you found yourself doing some sort of the same thing? If so, how?

Read More »

Code Smell Riddle #22

q. I have two sets of methods
that basically do the same work.
Change their name and code to match
Or I will certainly go berserk!

a. Parallel Inheritance Hierarchies

If you need help, here is a LIST of the remaining 2 Code Smells for this riddle series.

For a list of the 22 Code Smells feel free to visit the Code Smells website.

Post a comment with your guess :)

~/riddle by me

Read More »

Code Highlighters For Your Blog

I recently tweeted that I thought the SyntaxHighlighter is the best way to display code on your blog. In response, I had some who were a little confused how to get started with the tool. The tool isn't as straight forward as some other tools. There are several steps you will need to take in order for it to work on your blog.

Since my tweet, I have reconsidered my initial recommendation for new users. The look and features of SyntaxHighlighter are nice, but it does take some setup on your blog, some manual manipulation of your code, and presents a slight delay during render time (since it is dynamically manipulated via JavaScript).

I plan to start using SyntaxHighligher from now on and I would recommend it for bloggers that post a lot of code, but if you an occasional code poster, then one of the following Windows Live Writer plug-ins might be a better solution for you (they are much simpler and faster to render and takes no setup on your blog). All that said, you might even like the plug-ins better than SyntaxHighlighter... and hey, that's fine by me :)

The Windows Live Writer plug-ins that I recommend are...

Read More »

An NDepth Look @ NDepend

Synpopsis

I’ve been wanting to review NDepend for quite some time, but I figured it was bad form to run it against my production code from work.

So, instead of running the tool against my work code, I thought I’d use the PetShop ASP.NET MVC project that I created for the .NET User’s Group.

NDepend provides many ways to visualize the architecture of any particular project.  To create the following pictures and diagrams all I did was point NDepend to my Visual Studio solution file.

Dependency Graph

A useful way to get an understanding of how your application architecture is to generate a Dependency Graph based off your code. The following graph shows show the PetShop pieces relate to one another.

<div> </div>
Dependency Matrix

<div>For those of you who are graphically challenged, there is a Dependency Matrix that does a nice job of showing how many dependencies there are between 2 particular areas of your design.</div>
<div>  </div>
Code Metrics

<div>The next diagram has always impressed me. Even if you didn’t know what it meant… it is pretty impressive to just look at :) The following diagram is actually showing the Code Metrics for your project. The following image represents the number of lines of code (LOC) in your project.  </div>
<div></div>
CQL Queries

In addition to all these cool graphs, matrices, and images, there are some hard core queries that you can perform against your assemblies. NDepend has something called Code Query Language (CQL) that allows you to write custom queries to identify numerous statistics such as:
<ul><li>Which public methods have more than 30 lines of code?</li><li>Which classes implement System.IDisposable?</li><li>Which methods have been refactored recently and is not thoroughly covered by tests?</li><li>etc…
</li></ul>
<div> </div>
<div>The following is an example of what a CQL query looks like. This query identifies the methods that are too big in your assembly. NDepend comes with a library of already created queries, such as this one, but you are able to add to or customize these quieres as well. </div>
<div></div>
Conclusion

There is so many more features that I haven’t covered that NDepend provides, but I wanted to highlight some of the features that I thought are very useful and could help you in your current projects.

I think this tools adds some great functionality that dovetails nicely with the features of from the various Visual Studio suites.

Don’t just take my word for it, I encourage you to download a trial version of NDepend and check it out for yourself.

Then if you like it, make a list of the features that are useful for your project, show it to your boss, and see if your work will pay for it :)

Read More »

Code Smell Riddle #21

q. A collection of reusable methods,
Can be extremely handy when in a bind,
But can be all together aggravating,
When the desired one, you can not find!

a. Incomplete Library Class

For a list of the 22 Code Smells feel free to visit the Code Smells website.

Need help? Here is a list of remaining Code Smells for this riddle series.

Post a comment with your guess :)

~/riddle by me

Read More »