Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use unsafe code in safe contex?

I need to use SecureString for a Microsoft's class and i found the following code on the internet:

public static class SecureStringExt {     public static SecureString ConvertToSecureString(this string password)     {         if (password == null)             throw new ArgumentNullException("password");          unsafe //Red highlighted line         {             fixed (char* passwordChars = password)             {                 var securePassword = new SecureString(passwordChars, password.Length);                 securePassword.MakeReadOnly();                 return securePassword;             }         }     } } 

The only problem is that the unsafe keyword keeps throwing me error saying Cannot use unsafe construct in safe context. Unfortunately i couldn't find why is this happening...

Note: The above code runs in LINQPad but not in VS2013 (with resharper).

like image 487
CodeArtist Avatar asked Sep 20 '14 22:09

CodeArtist


People also ask

What is an unsafe and safe code?

Unsafe is a C# programming language keyword to denote a section of code that is not managed by the Common Language Runtime (CLR) of the . NET Framework, or unmanaged code. Unsafe is used in the declaration of a type or member or to specify a block code.

How do I allow unsafe code unity?

Create a file in your <Project Path>/Assets directory and name it smcs. rsp then put -unsafe inside that file. Save and close that file. Close and reopen Visual Studio and Unity Editor.

What is the use unsafe keyword?

The unsafe keyword denotes an unsafe context, which is required for any operation involving pointers.


1 Answers

I am not sure if you need unsafe code in that case (see answer of @mybirthname).

But when unsafe code is needed, it can be enabled in Project properties.

  • In the main menu, click Project and then <ProjectName> properties...
  • Click on the Build page.
  • Select Allow unsafe code.

Allow unsafe code

Or one can specify /unsafe compiler option explicitly.

like image 52
AlexD Avatar answered Sep 24 '22 18:09

AlexD