SoFunction
Updated on 2025-03-06

Four ways to generate GUID format in C#

Generation and format of GUID in C#

1. GUID is a structure body under the System namespace, and the examples are shown below.
(1) Create a GUID Help Class (GUIDHelper)

using System;
using ;
using ;
using ;

namespace 
{
  public class GuIdHelper
  {
    /// <summary>
    /// GUID generation    /// </summary>
    /// <param name="format">Format You can fill in N, D, B, P, X</param>    /// &lt;returns&gt;&lt;/returns&gt;
    public static string GetNewGuId(string format="")
    {
      if ((format))
        return ().ToString();
      else
        return ().ToString(format);
    }
  }
}

(2) Example

using System;
using ;
using ;
using ;
using ;
using ;
using ;

namespace 
{
  public partial class Index : 
  {
    protected void Page_Load(object sender, EventArgs e)
    {

      StringBuilder str = new StringBuilder();
      string[] array = {"","N","D","B","P","X" };
      foreach (var item in array)
      {
        if ((item))
          ("Default format:{0}", ());
        else
          ("&lt;br /&gt;{0}Format:{1}", item, (item));
      }
      (());
    }
  }
}

(3) Display the results

Default format: 4575c4b3-7997-4f11-acd9-f107258e9adc
N format: a53a7186b583483aa4580519034e8095
D format: 5ae7f002-a989-4345-864b-3bcfbe09e1da
B format: {d9762660-8461-4c44-b714-8ffad6e1b79c}
P format: (694ce704-0a7d-41d5-a25a-4eaedf7db50d)
X format: {0x75198f26, 0xac4e, 0x42c8, {0x96, 0x88, 0xcc, 0x91, 0xe0, 0xa6, 0x9b, 0x21}

Four formats for GUID generation in C#

var uuid = ().ToString(); // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12 
 
var uuidN = ().ToString("N"); // e0a953c3ee6040eaa9fae2b667060e09  
 
var uuidD = ().ToString("D"); // 9af7f46a-ea52-4aa3-b8c3-9fd484c2af12 
 
var uuidB = ().ToString("B"); // {734fd453-a4f8-4c5d-9c98-3fe2d7079760} 
 
var uuidP = ().ToString("P"); // (ade24d16-db0f-40af-8794-1e08e2040df3) 
 
var uuidX = ().ToString("X"); // {0x3fa412e3,0x8356,0x428f,{0xaa,0x34,0xb7,0x40,0xda,0xaf,0x45,0x6f}} 

refer to:/en-us/library/