I need a Guid property in some attribute class like this:
public class SomeAttribute : Attribute { private Guid foreignIdentificator; public Guid ForeignIdentificator { get { return this.foreignIdentificator; } set { this.foreignIdentificator = value; } } }
But in attribute definition I can use only primitive types, which are constants ( I understand why, and it’s make me sense ). The workaround can be definition ‘ForeignIdentificator’ as string, and creating Guid in runtime:
public class SomeAttribute : Attribute { private string foreignIdentificator; public string ForeignIdentificator { get { return this.foreignIdentificator; } set { this.foreignIdentificator = value; } } public Guid ForeignIdentificatorGuid { get { return new Guid( ForeignIdentificator ); } } }
Unahppily I loose check for type safety. The ‘ForeignIdentificator’ property can contains any string value and during creating Guid will be thrown exception at runtime, not at compile time.
I know the compiler checks string value for ‘System.Runtime.InteropServices.GuidAttribute’ for ‘Guid compatibility’. This check is exactly what I need, but I don’t know if this check i hardcoded in compiler or can me explicitly defined ( and how ).
Do you know some way, how to secure ‘Guid compatibilty’ check for attributes? Or some another way, how to reach type safe Guid definition in attributes? Thanks.
I have run into your exact problem in the past. We simply required them to pass in the GUID as a string… the default way that the VS GUID generator tool gives it to us (*F9168C5E-CEB2-4faa-B6BF-329BF39FA1E4). We essentially did what you did. We use it in a plug-in architecture, so our customers have been the ones to use the interface. If you look at what Microsoft does when they need to do the same thing, they do that.
It hasn’t been a problem to do it this way. Not once, have we seen this as an issue from the field.
You might want to name that string field GUID, though, as to not confuse your consumers. Add some documentation in case they don’t know what format it needs to be in.
I had the same reaction when I looked at this… but then I just moved on, as it seems there is no type-safe solution.