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

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

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.


Solution 1:

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)

Solution 2:

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