0

I am new to C# and don't.

Can someone please explain why passwordHash was able to be assigned to user.PasswordHash despite passwordHash only being declared as an argument of a method?

     public async Task<ServiceResponse<int>> Register(User user, string password)
        {
            CreatePasswordHash(password, out byte[] passwordHash, out byte[] passwordSalt);

            user.PasswordHash = passwordHash;
            user.PasswordSalt = passwordSalt;

            ...

        }

       private void CreatePasswordHash(string password, out byte[] passwordHash, out byte[] passwordSalt)
        {
            var hmac = new System.Security.Cryptography.HMACSHA256()
            using (hmac)
            {
                passwordSalt = hmac.Key;
                passwordHash = hmac.ComputeHash(System.Text.Encoding.UTF8.GetBytes(password));
            }
        }
Jim_Mcdonalds
  • 426
  • 5
  • 15

1 Answers1

1

In this case, passwordHash is passed an an "out" parameter, which means it has a value set by the method it's passed to, that can then be used for subsequent computation after the method completes. It's a way of, in effect, returning more than one thing from a method and is also how all the TryParse methods work.

See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-parameter-modifier for more.

Jeremy C.
  • 74
  • 4
  • 1
    Though the way we should "return more than one thing" is to use a custom type, or something built in like one of the various tuple offerings. The OP's code doesn't have the simplicity of TryParse so I would advocate not following its pattern – Caius Jard Jun 12 '21 at 05:39