One of the things I love about Ruby is inspect(). Suppose you have an object that returns an array:
Code:
result_of_query = Products.find_by_type('Power Tools')
One of the cool things about Ruby is that you can view the contents of the array in interactive ruby (irb):
Code:
puts results_of_query.inspect
By calling the inspect method, you get a nifty output, say like this:
Code:
['Drill','Nail Gun', ...]
One thing I'm missing in .NET is this stuff. When I'm writing test, it'd be nice to be able to return a string with a neatly formatted output of anything that implements IEnumerable.
But instead of whining, I went ahead and created my own Inspect method. But wouldn't it be cumbersome if I had to do this EVERYTIME?
Code:
string output = Helper.Inspect(myCollection);
So, using the power of Extension Methods, I wrote a quick and dirty function:
Code:
public static string Inspect<T>(this IEnumerable<T> list)
{
System.Text.StringBuilder sb = new StringBuilder();
List<string> items = new List<string>();
foreach (var item in list)
{
items.Add(item.ToString());
}
sb.Append(String.Join(",", items.ToArray()));
sb.Insert(0, "[");
sb.Insert(sb.Length, "]");
return sb.ToString();
}
It's nothing big. The extension method allows me to call this method from any IEnumerable object:
Code:
List<int> myInts = new List<int>(); myInts.Inspect();
The
only caveat is that because I'm using a generic type, any of my custom types won't be able to utilize this. So, I ask the user to override the ToString() method. I also created another property that exposes the name and value of the property:
Code:
public static string InspectProperties<T>(this T obj)
{
StringBuilder sb = new StringBuilder();
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach (PropertyInfo property in properties)
{
sb.AppendFormat("\"{0}\": \"{1}\" \n", property.Name, property.GetValue(obj, null));
}
return sb.ToString();
}
I created another extension method that is accessible through any object. Now, I'm only exposing properties (not methods) and getting their values. I do this because I write a lot of State Bags (POCO) that I use to shuttle data between my BLL and DAL's.
Tell me what you think! I'd like to start a discussion on the things that you do that make your dev day-to-day easy.