Thursday, 28 June 2012

.Net Tips : Validate GUID string and Improvement in GUID in .Net Framework 4

In .NET Framework 4 there is enhancement System.Guid structure, These includes new TryParse and TryParseExact methods. Using these methods you can validate GUID string.
GUID means a globally unique identifier (GUID). GUID is a structure and it's namespace is System.Guid. A GUID is a 128-bit integer this can be used in all computers and networks wherever a unique identifier is required. This identifier has a very less probability of being duplicated.


Here is example for this.
In this example we create new guid object and also take one string variable which has invalid guid. After that we use TryParse method to validate that both variable has valid guid format or not. By running example you can see that string variable has not valid guid format and it gives message of "InValid guid". If string variable has valid guid than this will return true in TryParse method.


C# Example :
        //Generate New GUID
        Guid objGuid = Guid.NewGuid();
        //Take invalid guid format
        string strGUID = "aaa-a-a-a-a";

        Guid newGuid;

        if (Guid.TryParse(objGuid.ToString(), out newGuid) == true)
        {
            Response.Write(string.Format("<br/>{0} is Valid GUID.", objGuid.ToString()));
        }
        else
        {
            Response.Write(string.Format("<br/>{0} is InValid GUID.", objGuid.ToString()));
        }

        
        Guid newTmpGuid;

        if (Guid.TryParse(strGUID, out newTmpGuid) == true)
        {
            Response.Write(string.Format("<br/>{0} is Valid GUID.", strGUID));
        }
        else
        {
            Response.Write(string.Format("<br/>{0} is InValid GUID.", strGUID));
        }

VB.net Example :
        'Generate New GUID
        Dim objGuid As Guid = Guid.NewGuid()
        'Take invalid guid format
        Dim strGUID As String = "aaa-a-a-a-a"

        Dim newGuid As Guid

        If Guid.TryParse(objGuid.ToString(), newGuid) = True Then
            Response.Write(String.Format("<br/>{0} is Valid GUID.", objGuid.ToString()))
        Else
            Response.Write(String.Format("<br/>{0} is InValid GUID.", objGuid.ToString()))
        End If


        Dim newTmpGuid As Guid

        If Guid.TryParse(strGUID, newTmpGuid) = True Then
            Response.Write(String.Format("<br/>{0} is Valid GUID.", strGUID))
        Else
            Response.Write(String.Format("<br/>{0} is InValid GUID.", strGUID))
        End If

Output :

This type of C# Tips is very useful in day to day programming life.

Note : Give Us your valuable feedback in comments. Give your suggestions in this article so we can update our articles accordingly that.




No comments:

Post a Comment