Tag: guid

  • My Favorite Extension Methods: IsGuid

    In this third installment of my Favorite Extension methods series, I will show how to quickly evaluate a string to determine if it is the string representation of a Guid.

    I came upon the need for this method because I am using ASP.NET MVC for an application that uses a Guid to identify a record. In a case where my controller method is to retrieve a record, the controller’s parameter is a string.

    <Extension()> _
    Public Function IsGuid(ByVal value as String) As Boolean
      If String.IsNullOrEmpty(value) Then
        Return False
      Else
        Try
          Dim guid As New Guid(value)
          Return True
        Catch Ex As Exception
          Return False
        End Try
    End Function

    Using this extension method, I can ensure that a string represents a Guid and I won’t encounter any errors when trying to Cast that value into a Guid.

    If Not recordGuid.IsGuid Then Throw New ArgumentException("RecordGuid must contain a Guid string.")