44

I've got a lot of code that is using GUIDs (an architecture handed to me--not my choice).

Mostly, the values come from a database and load into memory from there. However, I'm doing some testing and I'm hard-coding some GUIDs into the code.

I haven't found an easy way to assign GUIDs, so I've ended up using Guid.Parse("...."). Is there an easier way to assign GUIDS in C#?

value = Guid.Parse("11223344-5566-7788-99AA-BBCCDDEEFF00"); 

It just seems like a lot of overhead to create the string then parse it. I would think there would be an easier way to directly assign it.

2
  • 1
    Do you need the Guids to have specific values? If not, then... var myGuid = Guid.NewGuid();? Commented Jun 18, 2013 at 12:42
  • Yeah, unfortunately, I do. They're all tied back to database values (PKs and FKs, nonetheless). Not what I would've started with, but I didn't build the system myself. The code above is just a silly example, not directly from my codebase. Commented Jun 18, 2013 at 12:57

3 Answers 3

88

If you already have a string representation of the Guid, you can do this:

Guid g = new Guid("11223344-5566-7788-99AA-BBCCDDEEFF00"); 

And if you want a brand new Guid then just do

Guid g = Guid.NewGuid(); 
Sign up to request clarification or add additional context in comments.

2 Comments

Yeah, that's it. I suspect it's still doing a .Parse() underneath the covers, but at least it's cleaner in code. Thanks.
I'm sure you're right, but as you say, this looks cleaner. Also, have you seen Eric Lippert's blog series about Guids? It's quite interesting (I know you're stuck with them, so maybe not pertinent to you): blogs.msdn.com/b/ericlippert/archive/2012/04/24/…
1

In case you use the guid as a constant - you can put the guid in your project settings. enter image description here than you can reach you values the following way:

var myGuid = Properties.Settings.Default.MyGuid; 

Comments

0

if you go for the constant option you can use this Guid method (one of six available):

private static const Guid PUBLIC_KEY = new Guid((int)0x93EE8E7F, 0x13FA, 0x4C6D, new byte[] { 0x9D, 0x32, 0xE6, 0xEC, 0xD1, 0x4A, 0x91, 0xA7 }); // {93EE8E7F-13FA-4C6D-9D32-E6ECD14A91A7} 

1 Comment

If this is C# snippet then it will not compile because a const cannot be marked as static.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.