I have a small C# class with a few unsafe methods. Is there a way to specify "/unsafe" option declaratively in C# source code (with #pragma
or anyhow else) just for the context of the class' source file? I'd hate to create a separate assembly for such a small class, but I also really don't want the rest of the assembly (the class is currently a part of) to be enabled for unsafe code.
No, this is (currently) not possible, as the entire assembly is affected by having unsafe code in it.
By including unsafe code in your assembly, you are telling the CLR that the assembly could do something, well, unsafe, which changes how the runtime acts when it loads the assembly. The biggest change here is that the CLR will simply not try to verify your unsafe code, but it also will refuse to load your assembly unless it has full-trust (e.g. you couldn't load an unsafe assembly as a normal user over click-once.)
From a technical perspective, when you use the /unsafe
option, it causes the compiler to emit the IL equivalent of the following module-level attributes into your assembly:
[assembly:SecurityPermission(SkipVerification = true)]
[assembly:UnverifiableCode]
Your best option is, as you said, to isolate the unsafe code into its own separate assembly as much as possible. The fact that the assembly has only one class in it is much less of a code-smell than tainting an entire assembly full of safe code due to one unsafe class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With