Assigning a GUID in C#

Richard picture Richard · Jun 18, 2013 · Viewed 45.1k times · Source

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.

Answer

Tom Chantler picture Tom Chantler · Jun 18, 2013

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