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.
(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 aGuid. Then you can make the string representation of that particular Guid yourstringconstant.The
Guidis fixed, of course. A field markedconstis alwaysstatic(but you must not supply thestatickeyword; it is implied).If you want to have the field of
Guidtype, then it can’t be declaredconstin C#. Then you would do:readonlymeans that the field can only be changed from a (staticin this case) constructor of the same class (a constructor of a derived class is not OK).