C# Guid TryParse

Description

Guid TryParse converts the string representation of a GUID to the equivalent Guid structure.

Syntax

Guid.TryParse has the following syntax.


public static bool TryParse(
  string input,
  out Guid result
)

Parameters

Guid.TryParse has the following parameters.

  • input - The GUID to convert.
  • result - The structure that will contain the parsed value. If the method returns true, result contains a valid Guid. If the method returns false, result equals Guid.Empty.

Returns

Guid.TryParse method returns true if the parse operation was successful; otherwise, false.

Example

The following example creates a new GUID, converts it to three separate string representations by calling the ToString(String) method with the "B", "D", and "X" format specifiers, and then calls the TryParse method to convert the strings back to Guid values.


using System;//  w w w. jav a  2 s  .c  o m

public class Example
{
   public static void Main()
   {
      Guid originalGuid = Guid.NewGuid();
      string[] stringGuids = { originalGuid.ToString("B"),
                               originalGuid.ToString("D"),
                               originalGuid.ToString("X") };

      Guid newGuid;
      foreach (var stringGuid in stringGuids) {
         if (Guid.TryParse(stringGuid, out newGuid))
            Console.WriteLine("Converted {0} to a Guid", stringGuid);
         else
            Console.WriteLine("Unable to convert {0} to a Guid", 
                              stringGuid);
      }                                      
   }
}

The code above generates the following result.





















Home »
  C# Tutorial »
    System »




Array
BitConverter
Boolean
Byte
Char
Console
ConsoleKeyInfo
Convert
DateTime
DateTimeOffset
Decimal
Double
Enum
Environment
Exception
Guid
Int16
Int32
Int64
Math
OperatingSystem
Random
SByte
Single
String
StringComparer
TimeSpan
TimeZone
TimeZoneInfo
Tuple
Tuple
Tuple
Type
UInt16
UInt32
UInt64
Uri
Version