Proposal: anonymous value types #10315
Unanswered
hez2010
asked this question in
Language Ideas
Replies: 1 comment 13 replies
|
ValueTuple seems working enough? |
13 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.
Motivation
Currently in C# we can use anonymous types by omitting the type name when instantiating an object:
This synthesizes a class under the hood to hold the values. But this doesn't work in cases where the receiver type requires the object to be a struct.
For example:
This is very inconvenient.
Besides, we have many APIs in .NET that follows a design pattern which allows us to pass a state object separately when registering a delegate to avoid capturing, eg. ThreadPool.QueueUserWorkItem, etc. Allowing to use a struct here can enable both better runtime performance and less bloating.
A recent example that can benefit from anonymous value types immediately can be found here.
Proposal
new struct {}
Allowing struct based anonymous types by putting a
structafternew.The above code instantiate an object of anonymous value type. The compiler will sunthesize a struct instead of a class to hold the values.
And, if any ref field is used, the compiler will synthesize a ref struct instead.
Anonymous value types for struct constrained generics
When the receiver type is a generic parameter that is constrained with
structorunmanaged, instantiating an anonymous object at the callsite will use structs.Compatibility
This is a pure addition to the language without a breaking change.
All reactions