Search code examples
c#extension-methodsunsafesecurestring

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).


Solution

  • 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.