Runtime constants in attributes

Open
#108,416 8 comments 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
20/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
csharp
Domain
compilers

Research direction

Start with the linked ConcurrentQueueSegment.cs example and the csharplang discussions 343, 4652, and 776; no implementation file or test is named in the issue. Clarify which runtime-constant forms and purity requirements are supported, then define tests covering accepted and rejected attribute arguments.

Written by the indexing model from the issue text.

Description

area-TypeSystem-coreclr

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 (https://github.com/dotnet/csharplang/discussions/343), improved explicit layouts (https://github.com/dotnet/csharplang/discussions/4652), enabling users to do things like

https://github.com/dotnet/runtime/blob/7b1e788c34ee9a44f6dc548c170c153dd7eab559/src/libraries/System.Private.CoreLib/src/System/Collections/Concurrent/ConcurrentQueueSegment.cs#L339-L344

and more.


We don't currently have a way to declare a pure function. There is an old csharplang discussion about it (https://github.com/dotnet/csharplang/discussions/776), probably it's a new thing that would require runtime validation of purity.

Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.