Tag Archives: .NET

GuidHelper.TryParse

Microsoft has apparently added Guid.TryParse() to .NET 4.0, but if you’re stuck using an older version of the framework, you’re still kind of left flapping out in the wind.  Luckily, the great minds of the world have converged upon StackOverflow.com and provided a solution: call the Win32 function CLSIDFromString.

I have taken the code and created a little helper class with one public static method called TryParse.  Its usage is just like that of any other TryParse() method in the .NET Framework today.  Here is the code:

using System;
using System.Runtime.InteropServices;


/// <summary>
/// Class that encapsulates the Win32 function CLSIDFromString.
/// </summary>
public static class GuidHelper
{
    /// <summary>
    /// Converts the string representation of a GUID to its System.Guid equivalent.  A return value
    /// indicates whether the conversion succeeded.
    /// </summary>
    /// <param name="s">A string containing the GUID to convert.</param>
    /// <param name="value">When this method returns, contains the System.Guid value equivalent to
    /// the GUID contained in s, if the conversion succeeded, or Guid.Empty if the conversion
    /// failed. The conversion fails if the s parameter is null or is not of the correct format.
    /// This parameter is passed uninitialized.</param>
    /// <returns>true if s was converted successfully; otherwise, false.</returns>
    public static bool TryParse(string s, out Guid value)
    {
        if (string.IsNullOrEmpty(s))
        {
            value = Guid.Empty;
            return false;
        }


        // CLSIDFromString requires enclosing curly braces on its GUIDs.
        if (!s.StartsWith("{"))
        {
            s = "{" + s;
        }
        if (!s.EndsWith("}"))
        {
            s += "}";
        }


        int result = CLSIDFromString(s, out value);
        if (result >= 0)
        {
            return true;
        }
        else
        {
            value = Guid.Empty;
            return false;
        }
    }


    /// <summary>
    /// This function converts a string generated by the StringFromCLSID function back into the
    /// original class identifier.
    /// </summary>
    /// <param name="sz">String that represents the class identifier</param>
    /// <param name="clsid">On return will contain the class identifier</param>
    /// <returns>
    /// Positive or zero if class identifier was obtained successfully
    /// Negative if the call failed
    /// </returns>
    [DllImport("ole32.dll", CharSet = CharSet.Unicode, ExactSpelling = true, PreserveSig = true)]
    private static extern int CLSIDFromString(string sz, out Guid clsid);
}

Fair warning: I verified the author’s performance numbers, but I have not yet run this through a profiler or done any checking for memory leaks. Use it at your own risk.

I suppose since the original is licensed under the cc-wiki license with attribution required, this is, too.

Anyway, enjoy!

Some more LINQ love

Here’s another example of how I feel LINQ improves the readability of my code. This is the before version, using standard looping to populate a list of objects:

private IEnumerable&lt;Album&gt; ReadAlbums(LLAlbum[] llAlbums)
{
    Album album;
    IList&lt;Album&gt; albums = new List&lt;Album&gt;(llAlbums.Length);

    foreach (LLAlbum llAlbum in llAlbums)
    {
        album = new Album()
        {
            AlbumId = llAlbum.Id
        };

        albums.Add(album);
    }

    return albums;
}

And here is the after version, using a LINQ query:

private IEnumerable&lt;Album&gt; ReadAlbums(LLAlbum[] llAlbums)
{
    return from llAlbum in llAlbums
           select new Album
           {
               AlbumId = llAlbum.Id
           };
}

Now, depending on your familiarity with LINQ, you may or may not agree with me, but I love it!

try/swallow

Dear fellow coders,

Please don't ever do this:

private static void SomeFunc()
{
    try
    {
        DoSomething();
        DoSomethingElse();
    }
    catch
    {
        // eat the exception  &lt;– NO!  BAD CODER!
    }
}

Love,

Jon