How to declare a constant Guid in C#?

67.4k views Asked by At

Is it possible to declare a constant Guid in C#?

I understand that I can declare a static readonly Guid, but is there a syntax that allows me to write const Guid?

6

There are 6 answers

1
Quick Joe Smith On BEST ANSWER

No. The const modifier only applies to "primitive" types (bool, int, float, double, long, decimal, short, byte) and strings. Basically anything you can declare as a literal.

2
walt jimi On

While you can't seem to do that you can do that to be parsed whenever you need it:

const string _myGuidStr = "e6b86ea3-6479-48a2-b8d4-54bd6cbbdbc5";
2
Jaime Botero On

Declare it as static readonly Guid rather than const Guid

3
Stefan On
public static readonly Guid Users = new Guid("5C60F693-BEF5-E011-A485-80EE7300C695");

and that's that.

3
ProVega On

I am doing it like this:

public static class RecordTypeIds
{
    public const string USERS_TYPEID = "5C60F693-BEF5-E011-A485-80EE7300C695";
    public static Guid Users { get { return new Guid(EntityTypeIds.USERS_TYPEID); } }
}
0
Denise Skidmore On

Depends on what you want a const for.

If you want to have a known GUID that you can reuse as needed, the above solution of storing the GUID as a string and parsing to GUID as needed works.

If you need a default parameter value, that won't work. The alternative is to use a nullable Guid and use null as your constant value.

public void Foo(string aParameter, Guid? anOptionalGuid = null)