How to use unsafe code in safe contex?

16,185

Solution 1

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.

Solution 2

    public static SecureString GetSecureString(string password)
    {
        SecureString secureString = new SecureString();

        foreach (char c in password)
        {
            secureString.AppendChar(c);
        }

        secureString.MakeReadOnly();
        return secureString;
    }

You can make same thing without unsafe code.

Share:
16,185
CodeArtist
Author by

CodeArtist

Full stack developer using platforms: C#, ASP.Net - MVC - WebApi - OData, EF Javascript family: Javascript, jQuery, Bootstrap, AngularJs, Appcelerator Titanium SQL Server Python/Django CSS Knowledge is power.

Updated on June 02, 2022

Comments

  • CodeArtist
    CodeArtist about 2 years

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