[C # delicious] What is the Guid ToString format ?,

Source: Internet
Author: User

[C # delicious] What is the Guid ToString format ?,

In daily programming, Guid is commonly used. The most common usage is as follows:

string id = Guid.NewGuid().ToString();

This statement generates a new Guid and converts it to a string, as shown below:

// 10244798-9a34-4155-b1ef-9143f9b1e68a

However, in some cases, we may have some differences in details, such:

  • Braces {xxxxxxxx-xxxx-xxxxxxxxxxxx}
  • There is no hyphen between xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  • Parentheses (xxxxxxxx-xxxx-xxxxxxxxxxxx)

In this case, it is quite troublesome. The most common one is to parse the string generated by the guid, such as adding parentheses or replacing the hyphen with null characters:

var str = guid.ToString();var id = "{" + str + "}";var id2 = str.Replace("-", "");var id3 = "(" + str + ")";

 

In fact, this is not so troublesome. In ToString, there is an overloaded function:

ToString(String)

You can input a formatted string to output this type of guid.

Example:

var guid = Guid.NewGuid();// 10244798-9a34-4245-b1ef-9143f9b1e68aConsole.WriteLine(guid.ToString("D"));// 102447989a344245b1ef9143f9b1e68aConsole.WriteLine(guid.ToString("N"));// {10244798-9a34-4245-b1ef-9143f9b1e68a}Console.WriteLine(guid.ToString("B"));// (10244798-9a34-4245-b1ef-9143f9b1e68a)Console.WriteLine(guid.ToString("P"));

 

Note: The values D, N, B, and P are case-insensitive. If an empty string is input, the default D type is used. Exceptions are reported in other cases.

There is also an "X" type found in MSDN, but an exception will pop up when I use it in. NetFx 3.5:

Unprocessed exception: System. formatException: the format string can only be "D", "d", "N", "n", "P", "p", "B", or "B ".
In System. Guid. ToString (String format, IFormatProvider provider)
The article forwarded micro-blog: http://www.cnblogs.com/greenerycn/archive/2010/04/25/guid_tostring_format.html (original)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.