Extension Methods are Your Friends

That's it.  I've had it.  I'm sick of constantly creating arrays with one object in them just so I can call Vault API functions.  No more, I say!  Thanks to the extension method feature of .NET, I can now create a method on object to easily do this for me. 

LINQ already gives me FirstOrDefault that lets me convert an array to a single value.  Here is a function that does the inverse.

internal static class ExtensionMethods
{
    internal static T[] ToSingleArray<T>(this T obj)
    {
        return new T[] { obj };
    }
}

Here is a comparison between the default way and the extension method way:

// instead of this
docSvc.FindLatestFilesByPaths(new string[] { "$/drawing.dwg" });

// I can use the extension method
docSvc.FindLatestFilesByPaths("$/drawing.dwg".ToSingleArray());

Looking at the code, it doesn't look like one is better than the other.  But when you are typing the code out, the extension method makes things much easier.  You don't have to fiddle with []{} characters and intellesense will type most of the function name for you.

This is just a basic example of a powerful feature.  There are tons of uses and misuses for extension methods, so make sure to read up on it in MSDN. 


Here is another method you might find useful when Vault passes back an array and you want to see if there is any data in it.

internal static bool IsNullOrEmpty<T>(this IEnumerable<T> collection)
{
    return collection == null || collection.Count() == 0;
}

If you have any good ones that are helpful when programming Vault, post them in the comments section.


Comments

Leave a Reply

Discover more from Autodesk Developer Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading