How to convert a GUID to a string in C#?

前端 未结 10 909
挽巷
挽巷 2020-12-15 02:20

I\'m new to C#.

I know in vb.net, i can do this:

Dim guid as string = System.Guid.NewGuid.ToString

In C#, I\'m trying to do

相关标签:
10条回答
  • 2020-12-15 03:08

    According to MSDN the method Guid.ToString(string format) returns a string representation of the value of this Guid instance, according to the provided format specifier.

    Examples:

    • guidVal.ToString() or guidVal.ToString("D") returns 32 hex digits separated by hyphens: 00000000-0000-0000-0000-000000000000
    • guidVal.ToString("N") returns 32 hex digits:00000000000000000000000000000000
    • guidVal.ToString("B") returns 32 hex digits separated by hyphens, enclosed in braces:{00000000-0000-0000-0000-000000000000}
    • guidVal.ToString("P") returns 32 hex digits separated by hyphens, enclosed in parentheses: (00000000-0000-0000-0000-000000000000)
    0 讨论(0)
  • 2020-12-15 03:09

    Did you write

    String guid = System.Guid.NewGuid().ToString;
    

    or

    String guid = System.Guid.NewGuid().ToString();
    

    notice the paranthesis

    0 讨论(0)
  • 2020-12-15 03:10
    Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
    string guidValue = guidId.ToString("D"); //return with hyphens
    
    0 讨论(0)
  • 2020-12-15 03:13

    In Visual Basic, you can call a parameterless method without the braces (()). In C#, they're mandatory. So you should write:

    String guid = System.Guid.NewGuid().ToString();
    

    Without the braces, you're assigning the method itself (instead of its result) to the variable guid, and obviously the method cannot be converted to a String, hence the error.

    0 讨论(0)
提交回复
热议问题