Colin Bowern

... more of the usual bool

  Home  |   Contact  |   Syndication    |   Login
  23 Posts | 0 Stories | 13 Comments | 24 Trackbacks

News

Archives

Post Categories

I love the new TryParse methods in the .NET Framework 2.0.  It's too bad that not all types have a TryParse method.  There was a piece of feedback posted on MSDN about implementing one for Guid values.  Here's one I threw together for Guid values.  Feedback always appreciated:

 

/// <summary>
/// Converts the string representation of a Guid to its Guid 
/// equivalent. A return value indicates whether the operation 
/// succeeded. 
/// </summary>
/// <param name="s">A string containing a Guid to convert.</param>
/// <param name="result">
/// When this method returns, contains the Guid value equivalent to 
/// the Guid contained in <paramref name="s"/>, if the conversion 
/// succeeded, or <see cref="Guid.Empty"/> if the conversion failed. 
/// The conversion fails if the <paramref name="s"/> parameter is a 
/// <see langword="null" /> reference (<see langword="Nothing" /> in 
/// Visual Basic), or is not of the correct format. 
/// </param>
/// <value>
/// <see langword="true" /> if <paramref name="s"/> was converted 
/// successfully; otherwise, <see langword="false" />.
/// </value>
/// <exception cref="ArgumentNullException">
///        Thrown if <pararef name="s"/> is <see langword="null"/>.
/// </exception>
public static bool GuidTryParse(string s, out Guid result)
{
    if (s == null)
        throw new ArgumentNullException("s");
    Regex format = new Regex(
        "^[A-Fa-f0-9]{32}$|" + 
        "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
        "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$");
    Match match = format.Match(s);
    if (match.Success)
    {
        result = new Guid(s);
        return true;
    }
    else
    {
        result = Guid.Empty;
        return false;
    }
}
posted on Wednesday, January 18, 2006 7:40 PM

Feedback

# re: Guid TryParse 4/27/2007 12:49 PM Chris Mohan
Thanks for posting this. I took your implementation and made it a little more conscise (plus removed the throw so the caller can wrap the call in an if statement and throw as needed.)

public static bool GuidTryParse( string s, out Guid result ) {
result = Guid.Empty;
if ( string.IsNullOrEmpty( s ) || !( new Regex( _guidMatchPattern ) ).IsMatch( s ) ) { return false; }
result = new Guid( s );
return true;
}

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: