web 2.0

Utility Extension Methods cont’d

I rather enjoy this theme.  I find extension methods very useful when you have to repeat the same short group of code again & again.  Here a few other extension methods that I find handy.

  1. GetSOAPObjects<T>

    clip_image002

    This method is a personal favorite of mine.  My current employer requires that I pull a large amount of data from web services.  I usually check for web service unique errors before calling this method but in this example, i have wrapped logic into this method.  Most SOAP web services that I have encountered returns a custom object with both an error and results property.  You are usually returned an array of “Result” objects from the web service, but for most lightweight queries you will only ever use the first item.  Usually the results property is an array object that contains data only if the error object is null.  This method allows me to convert the results to an IEnumerable.  I am definitely not stating that this method covers every case, but it does cover most of my personal use cases.

    public static IEnumerable<T> GetSOAPObjects<T>(this ReadResult[] results)
    { 
        return  (results.FirstOrDefault() == null) 
            ? new Collection<T>() 
            : results.FirstOrDefault().objects.Cast<T>(); 
    }

     

  2. NullorArray<T>

    This method is simple.  I have a few cases where I have to convert an IEnumerable from a LINQ query to an array.  This is definitely the case for web services.  My issue was that I was required to call ToArray<T>() in the middle of a nested object initializer. I’d rather call an extension method than always try and wrap the logic for the multiple calls.

    public static T[] NullorArray<T>(this IEnumerable<T> inputCollection) 
    { 
        return (inputCollection == null) 
            ? null 
            : inputCollection.ToArray<T>(); 
    }

     

  3. ToStandardInt

    This method is almost identical to the extension method ToStandardBool I mentioned in the original article.  This takes a “string” value that represents an integer and returns 0 in all cases where it cannot be parsed.  I was not sure about the behavior or Int32.TryParse() on a null or empty string value, so I put in an extra layer of validation.

    public static int ToStandardInt(this string thisInt)
    { 
        int retVal = 0; 
        return String.IsNullOrEmpty(thisInt) 
            ? 0 
            : Int32.TryParse(thisInt, out retVal) 
                ? retVal 
                : 0; 
    }

     

  4. ToObjFmtString

    This is a very fun method.  I wrote it for a project where I had non-programmers who wanted to be able to read my code.  I tend to use StringBuilder.AppendFormat() and String.Format() a lot! I found that writing a method that makes string formatting a little more obvious to my non-programmer code reviewers helped out a bit.  So here’s an example:

    String.Format(*, obj)  
    String.Format(“{0} has {1} apples”, bob.name, bob.appleCnt);
    obj.ToObjFmtString(*)  
    bob.ToObjFmtString(“{name} has {appleCnt} apples”);

    This method allows me to put in the name of properties as opposed to indexes of an array.  It’s very helpful for simple String formatting.  You do lose all of the integer and padding customizations with the original method but gain a large amount of readability.  To pull this off, I used simple reflection and a regex.

    public static String ToObjFmtString(this Object obj, string format)
    { 
        return Regex.Replace
        (
            format, 
            @"\{(.*?)\}", 
            delegate(Match m) 
            { 
                return obj.GetType().GetProperty(m.Groups[1].ToString())
                        .GetValue(obj, null).ToString(); 
            }
        ); 
    }

     

What extension methods does everyone else use?  I am highly curious as to how people are using this cool new C# 3.0 feature.

Tags: ,

.NET | C#