-
Notifications
You must be signed in to change notification settings - Fork 1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Proposal: stack-only struct #231
Comments
What's the use case for this? Isn't it in effect just a less explicit and more limited (e.g. likely not usable in Also, how do you ensure the structure is really stack-only and cannot be for example instantiated using |
What are some use cases for this? How would it work with |
@svick stackonly struct A
{
FileStream file;
public A(string filename)
{
file = new FileStream(filename, FileMode.Open);
}
...... //other operation functions
~A()
{
if(file)
{
file.Close();
file=null;
}
}
} |
What if I need to keep your Forcing something to only be able to stay on the stack limits it's use considerably. |
@yaakov-h |
I don't think that would, because the compiler-generated state machine is a class. |
@yaakov-h |
remind me of |
It will allow to encapsulate refs and Spans |
struct A
{
int value;
// Error CS8170
ref int Value => ref value;
// OK, but should this be error if Span<T> becomes stack-only?
unsafe Span<byte> AsBytes() => new Span<byte>(Unsafe.AsPointer(ref value), 4);
}
stackonly struct B
{
int value;
// Could this be OK?
ref int Value => ref value;
// OK?
unsafe Span<byte> AsBytes() => new Span<byte>(Unsafe.AsPointer(ref value), 4);
} |
ref struct in C# 7.2 has implemented stack-only struct, but seems not to support finalizer. I will close this and open another issue. |
C# should provide stack-only struct, which can only be stored in stack, and can't be embedded in any class (but can be embedded in another stack-only struct).
This kind of stack-only struct can have destructor method, which would be executed when the struct goes out of scope.
For example:
The text was updated successfully, but these errors were encountered: