1

I would like to write some unsafe C# code for the purpose of writing high-performance, low-level libraries.

But I don't quite understand the limitations of where that code can run.

Microsoft obviously writes libraries that use unsafe code, which are fully trusted. Is Microsoft the only one who can do that?

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466
  • "which are fully trusted" - please clarify exactly what you mean by that. – Dai Apr 16 '22 at 21:08
  • @Dai: I'm having a lot of trouble finding a clear definition of that. It's just part of the information I found. You can see a discussion of trusted code [here](https://stackoverflow.com/questions/376049/what-is-a-partially-trusted-assembly-application-code-etc-in-net). – Jonathan Wood Apr 17 '22 at 15:08
  • The page you linked to refers to Partial-Trust and was part of Code Access Security, which Microsoft removed from .NET when .NET Core came out (because no-one was using it and it didn't really add any real security). And even then, the FullTrust vs. PartialTrust thing is at the full control of the sysadmin (it just means editing `machine.config`) - it has nothing to do with whoever originally authored the assemblies (be it Microsoft or otherwise). – Dai Apr 20 '22 at 03:27

1 Answers1

1

But I don't quite understand the limitations of where that code can run.

The unsafe code should be able to run anywhere were .NET can run.

Is Microsoft the only one who can do that?

Anybody can write the unsafe code. Though you should be careful cause there is a reason why it is called "unsafe" and you should fully understand what you are doing. The only "limitation" is that you need to add AllowUnsafeBlocks compiler option to the project using unsafe keyword.

Also note that with introduction of Span and Memory and corresponding APIs you should be able handle at least some high-performance scenarios without need for using unsafe directly.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Are you saying I could write a NuGet package that implements unsafe code, and anyone could use that package in any of their applications without taking additional steps? – Jonathan Wood Apr 17 '22 at 15:10
  • @JonathanWood AFAIK yes with the same rules applied to it as any other nuget. – Guru Stron Apr 17 '22 at 18:45