struct
as const
#4814
Unanswered
bryancostanich
asked this question in
Language Ideas
Replies: 1 comment 6 replies
-
As of now this is largely a runtime constraint. A literal field is only permitted to be one of a small subset of types that are understood by the runtime. The C# compiler does workaround this limitation in some cases, such as |
Beta Was this translation helpful? Give feedback.
6 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Hey all (FYI rewrote this based on new ideas)!
Use Case
I have the following use case, I'd like to be able to use structs as compile time constants in method arguments like the following:
Discussion
This has gnawed at me for a long time, but it has recently been causing API design headaches in Meadow. I naively thought that the challenge was that you can't declare a
struct
asconst
. But you can declare primitives, e.g.:Allowed:
Not allowed:
Naive Approach
I understand that this happens at compile time and the compiler is supposed to compile, not execute code, but maybe we could add some
const
initializer syntax or something? so we could do something like:alternatively, we could add an implicit operator, and have the compiler make sure that it's just a value set:
In the end, the compiler is also serializing primitive types into IL, so why can't we serialize our value into this? as long as it didn't actually do any code execution, just value setting, then this would be possible, no?
Other (Better?) Approach
However, as pointed out by @CyrusNajmabadi, there may be another approach here that would work, which is to update the runtime and complier to reference
static readonly
fields in those locations.I don't know the internals of the compiler/runtime well, I just know how I'd like to be able to code these APIs, so I'm open to approaches.
Thanks for reading.
Beta Was this translation helpful? Give feedback.
All reactions