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

前端 未结 10 908
挽巷
挽巷 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 02:47

    you are missing () on the end of ToString.

    0 讨论(0)
  • 2020-12-15 02:58

    You need

    String guid = System.Guid.NewGuid().ToString();
    
    0 讨论(0)
  • 2020-12-15 03:02
    String guid = System.Guid.NewGuid().ToString();
    

    Otherwise it's a delegate.

    0 讨论(0)
  • 2020-12-15 03:02

    Following Sonar rules, you should whenever you can try to protect yourself, and use System.globalisation whenever it's possible like for DateTime.ToString().

    So regarding the other answers you could use:

    guid.ToString("", CultureInfo.InvariantCulture)
    

    where "" can be replaces by : N, D, B , P and X for more infos see this comment.

    Example here

    0 讨论(0)
  • 2020-12-15 03:04

    Here are examples of output from each of the format specifiers:

    N: cd26ccf675d64521884f1693c62ed303
    D: cd26ccf6-75d6-4521-884f-1693c62ed303
    B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
    P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
    X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}
    

    The default is D.

    Run this yourself.

    0 讨论(0)
  • 2020-12-15 03:05

    You're missing the () after ToString that marks it as a function call vs. a function reference (the kind you pass to delegates), which incidentally is why c# has no AddressOf operator, it's implied by how you type it.

    Try this:

    string guid = System.Guid.NewGuid().ToString();
    
    0 讨论(0)
提交回复
热议问题