Why do I get the error "Unsafe code may only appear if compiling with /unsafe"?
Asked Answered
A

8

159

Why do I get the following error?

Unsafe code may only appear if compiling with /unsafe"?

I work in C# and Visual Studio 2008 for programming on Windows CE.

Arise answered 8/1, 2010 at 8:49 Comment(2)
B
300

To use unsafe code blocks, the project has to be compiled with the /unsafe switch on.

Open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox.

Brannen answered 8/1, 2010 at 9:7 Comment(4)
I must say, even though that does enable the build to compile, it still doesn't allow it to get published to the web :/Twain
@Nick: Yes, if you publish code to be compiled dynamically, then the project settings doesn't apply. See #16567697Brannen
Note that the settings might differ between Debug and Release compile. This just cost me 20 minutes of my life.Kolivas
You may have to change the build configuration from Debug to Release for different type of buildsWalford
F
135

Here is a screenshot:

Unsafe screenshot

ََََََََ

Feck answered 21/7, 2011 at 5:59 Comment(1)
Important: Also be aware that this screenshot is for "Configuration: Active (Debug)". You'll probably also need to change it for "Release", since that's most likely what you're publishing.Austrasia
B
5

Can also add AllowUnsafeBlocks tag to PropertyGroup directly in .csproj file

<PropertyGroup>
    <TargetFrameworks>netcoreapp3.1; net472</TargetFrameworks>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>
Bellboy answered 8/11, 2022 at 8:23 Comment(0)
R
4

Probably because you're using unsafe code.

Are you doing something with pointers or unmanaged assemblies somewhere?

Riva answered 8/1, 2010 at 8:52 Comment(0)
B
4

Search your code for unsafe blocks or statements. These are only valid is compiled with /unsafe.

Beaverboard answered 8/1, 2010 at 8:52 Comment(0)
D
4

To use unsafe code blocks, open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox, then compile and run.

class myclass
{
     public static void Main(string[] args)
     {
         unsafe
         {
             int iData = 10;
             int* pData = &iData;
             Console.WriteLine("Data is " + iData);
             Console.WriteLine("Address is " + (int)pData);
         }
     }
}

Output:

Data is 10
Address is 1831848
Dunedin answered 5/11, 2010 at 9:31 Comment(0)
F
3

For everybody who uses Rider you have to select your project>Right Click>Properties>Configurations Then select Debug and Release and check "Allow unsafe code" for both.Screenshot

Fleuron answered 22/4, 2018 at 10:17 Comment(0)
M
0

I add this Line to Project file <AllowUnsafeBlocks>true</AllowUnsafeBlocks> it work for me.

Merrythought answered 6/3, 2024 at 8:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.