views:

612

answers:

2

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?

+1  A: 

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.

Ian Kemp
AFAIK, a string must be readonly as well and can't be const.
Stefan Steinegger
Nope, you can have const strings.
Mattias S
Since the `string` I declared above is constant, it's compiled into the application and hence is available for use in `Attributes`.
Ian Kemp
so the solution is to put the string into a const, and pass it instead of a guid as argument, then the guid is instantiated in the constructor of the attribute?
Stefan Steinegger
Correct. Because the string is constant, the Guid constructed from that string must therefore also be constant. Hence it all works happily at compile time.
Ian Kemp
+1  A: 

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.

Dmytrii Nagirniak
Yes, this would be great, but what "other type" would it be?
Stefan Steinegger
Well, it would be string. But of course the GUID would not be type-safe.
Dmytrii Nagirniak