I have a project, where I need to work with unsafe memory buffers. So I have code like this in my project multiple times:
var buffer = new bytes[255];
unsafe
{
fixed (byte* bytes = buffer)
{
}
}
Please, make it shorter:
var buffer = new bytes[255];
unsafe fixed (byte* bytes = buffer)
{
}
or allow to skip unsafe
keyword (why we need it, if project has enabled unsafe context in settings?)
You can place the unsafe keyword on the class, or the method in question is that not sufficient?
So this proposal is to change the syntax of unsafe-statement to the following:
unsafe-statement:
unsafe
embedded-statement
Since embedded-statement already includes block it wouldn't be necessary to include both. That should allow for the unsafe
keyword to be immediately followed by another statement. Aside from fixed
this might also be useful when invoking an unsafe method without having to make the entire method unsafe or to declare a block with nested indentation:
unsafe void Bar(int* p) { ... }
void Foo() {
int i = 123;
unsafe Bar(&i);
}
But then it looks like unsafe
is a modifier on the call and there might be an expectation that the statement could be used as an expression:
unsafe int Bar(int* p) { ... }
void Foo() {
int i = 123;
int result = unsafe Bar(&i); // d'oh!
}
To avoid all of that the proposal could be narrower, such as:
unsafe-statement:
unsafe
block
unsafe
fixed-statement
Which would give you the ability to immediately follow unsafe
with fixed
but without allowing for other potential syntax benefits.
Of course, as @mburbea described, since you can apply unsafe
to the method or class outright, you can avoid most of the verbosity anyway.
@HaloFour Yep, you're absolutely right. It's all about these curly brackets. Just little syntax sugar.
Most helpful comment
So this proposal is to change the syntax of unsafe-statement to the following:
Since embedded-statement already includes block it wouldn't be necessary to include both. That should allow for the
unsafe
keyword to be immediately followed by another statement. Aside fromfixed
this might also be useful when invoking an unsafe method without having to make the entire method unsafe or to declare a block with nested indentation:But then it looks like
unsafe
is a modifier on the call and there might be an expectation that the statement could be used as an expression:To avoid all of that the proposal could be narrower, such as:
Which would give you the ability to immediately follow
unsafe
withfixed
but without allowing for other potential syntax benefits.Of course, as @mburbea described, since you can apply
unsafe
to the method or class outright, you can avoid most of the verbosity anyway.