Gold
Gold

Reputation: 62424

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

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.

Upvotes: 165

Views: 171373

Answers (8)

Ahmadreza Farrokhnejad
Ahmadreza Farrokhnejad

Reputation: 2390

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

Upvotes: 1

Manish
Manish

Reputation: 1775

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

<PropertyGroup>
    <TargetFrameworks>netcoreapp3.1; net472</TargetFrameworks>
    <AllowUnsafeBlocks>true</AllowUnsafeBlocks>
</PropertyGroup>

Upvotes: 8

Tobias Brohl
Tobias Brohl

Reputation: 519

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

Upvotes: 3

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

Upvotes: 4

Manoj Attal
Manoj Attal

Reputation: 2826

Here is a screenshot:

Unsafe screenshot

ََََََََ

Upvotes: 137

Guffa
Guffa

Reputation: 700152

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.

Upvotes: 308

Richard
Richard

Reputation: 108975

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

Upvotes: 4

Gerrie Schenck
Gerrie Schenck

Reputation: 22368

Probably because you're using unsafe code.

Are you doing something with pointers or unmanaged assemblies somewhere?

Upvotes: 4

Related Questions