-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Description
Currently, attributes only allow compile-time constants as constructor arguments/properties. If we were allowed to use runtime constants, attributes would become much more powerful.
What is considered a runtime constant? Existing consts, obviously, but also any static readonly field (which the tier-1 JIT treats as consts), as well as static pure functions* and properties (e.g. IntPtr.Size), and constant expressions (e.g. IntPtr.Size * 2).
This would enable things like lambdas in attributes (dotnet/csharplang#343), improved explicit layouts (dotnet/csharplang#4652), enabling users to do things like
Lines 339 to 344 in 7b1e788
| [StructLayout(LayoutKind.Explicit, Size = 3 * Internal.PaddingHelpers.CACHE_LINE_SIZE)] // padding before/between/after fields | |
| internal struct PaddedHeadAndTail | |
| { | |
| [FieldOffset(1 * Internal.PaddingHelpers.CACHE_LINE_SIZE)] public int Head; | |
| [FieldOffset(2 * Internal.PaddingHelpers.CACHE_LINE_SIZE)] public int Tail; | |
| } |
and more.
We don't currently have a way to declare a pure function. There is an old csharplang discussion about it (dotnet/csharplang#776), probably it's a new thing that would require runtime validation of purity.