Search code examples
c#compiler-errorsconstantsguid

Generate a Guid on compile time


I am trying to generate a constant value that I will be using like following:

public class Foo()
{
    public const String ExtensionKey = Guid.NewGuid().ToString();
    public int ID { get; set; }
}

The compiler is throwing an error:

The expression being assigned to 'Foo.ExtensionKey' must be constant

I know that it is not possible to execute a method (a constructor or a type initializer) at compile time. I am looking for a workaround to get randomly generated Guid assigned to different ExtensionKey constants of different classes.

EDIT:

The intention is to generate a UNIQUE Guid per type. The Guid value must be the same for all objects instances and whenever the application run. This is the behavior of Const and I am looking for a way to respect it.


Solution

  • (Much of this answer "promoted" from a comment to the question.)

    In Visual Studio, you can choose "Tools" - "Create GUID". Or in Windows PowerShell you can say [Guid]::NewGuid().ToString(). That will give you a Guid. Then you can make the string representation of that particular Guid your string constant.

    public const string ExtensionKey = "2f07b447-f1ba-418b-8065-5571567e63f6";
    

    The Guid is fixed, of course. A field marked const is always static (but you must not supply the static keyword; it is implied).

    If you want to have the field of Guid type, then it can't be declared const in C#. Then you would do:

    public static readonly Guid ExtensionKey = new Guid("2f07b447-f1ba-418b-8065-5571567e63f6");
    

    readonly means that the field can only be changed from a (static in this case) constructor of the same class (a constructor of a derived class is not OK).