开发者

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

开发者 https://www.devze.com 2022-12-11 02:00 出处:网络
I\'m new to C#. I know in vb.net, i can do this: Dim guid as string = System.Guid.NewGuid.T开发者_如何学GooString

I'm new to C#.

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

Dim guid as string = System.Guid.NewGuid.T开发者_如何学GooString

In C#, I'm trying to do

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

but i get an "Cannot convert method group 'ToString' to non-delegate type 'string'. Did you intend to invoke the method?" error.


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)


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();


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.


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.


Did you write

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

or

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

notice the parenthesis.


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

Otherwise it's a delegate.


You need

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


you are missing () on the end of ToString.


Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens


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

精彩评论

暂无评论...
验证码 换一张
取 消