C# Guid TryParseExact

Description

Guid TryParseExact converts the string representation of a GUID to the equivalent Guid structure, provided that the string is in the specified format.

Syntax

Guid.TryParseExact has the following syntax.


public static bool TryParseExact(
  string input,/*ww  w  .  j a va2s. c om*/
  string format,
  out Guid result
)

Parameters

Guid.TryParseExact has the following parameters.

  • input - The GUID to convert.
  • format - One of the following specifiers that indicates the exact format to use when interpreting input: "N", "D", "B", "P", or "X".
  • 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.TryParseExact method returns true if the parse operation was successful; otherwise, false.

Example

The following example calls the ToString(String) method with each of the supported format specifiers to generate an array of strings that represent a single GUID.


using System;/*from ww  w  .ja va  2 s  .c om*/

public class Example
{
   public static void Main()
   {
      string[] formats = { "N", "D", "B", "P", "X" };
      Guid guid = Guid.NewGuid();

      string[] stringGuids = new string[formats.Length];
      for (int ctr = 0; ctr < formats.Length; ctr++)
         stringGuids[ctr] = guid.ToString(formats[ctr]);

      foreach (var stringGuid in stringGuids) {
         Guid newGuid;
         if (Guid.TryParseExact(stringGuid, "B", out newGuid))
            Console.WriteLine("Successfully parsed {0}", stringGuid);
         else 
            Console.WriteLine("Unable to parse '{0}'", 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