Question

How can I use a static Guid as argument in an attribute?

static class X
{
  public static readonly Guid XyId = new Guid("---");
}

[MyAttribute(X.XyId)] // does not work
public class myClass
{
}

It does not work because Guid must be readonly, it can not be const. The string and byte[] representation would also be readonly.

Is there any workaround for this?

Was it helpful?

Solution

It's not possible and will never be possible, because [Attributes] are compiled as metadata and static variables are initialized at runtime, and of course the former cannot access the latter (except via Reflection).

If the standard

public const string MyGuid = "blah";

won't work for you, then AFAIK the only way to achieve what you want, is with Reflection.

OTHER TIPS

Unfortunately there is no a good way to pass Guid to attribute. Only workaround would be to use another type for that and convert it to Guid.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top