Skip to content

Runtime constants in attributes #108416

@timcassell

Description

@timcassell

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

[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.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions