Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: static Guid as argument of an attribute

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?

like image 364
Stefan Steinegger Avatar asked Jan 23 '23 05:01

Stefan Steinegger


1 Answers

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.

like image 133
Ian Kemp Avatar answered Jan 30 '23 09:01

Ian Kemp