Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I get this error:
"An object reference is required for the non-static field, method, or property 'HashAlgorithm.ComputeHash(byte[])'"

on this code:
C#
protected void Button1_Click(object sender, EventArgs e)

    {

        HashAlgorithm.Create("SHA512");
        byte[] hash = HashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(PIN_Entry.Text));
        string MyHash = System.BitConverter.ToString(hash);
        MessageBox.Show(MyHash.Replace(" ", ""));
    }


What I have tried:

tried all the built in potential fixes within Visual Studio but they just bring over errors. I am just not sure how to add the object reference that Visual Studio complains about. I just add characters to a TextBox then click a button to hash that text. Any ideas would be appreciated. the message box line is just for testing purposes and will be removed in the final code.
Posted
Updated 10-Feb-22 10:19am
v2

Try this

HashAlgorithm myHashAlgorithm = HashAlgorithm.Create("SHA512");
byte[] hash = myHashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(PIN_Entry.Text));
string MyHash = System.BitConverter.ToString(hash);
MessageBox.Show(MyHash.Replace(" ", ""));
 
Share this answer
 
v2
Comments
Michaelred54 11-Feb-22 7:26am    
Thank you. That did it. I feel like I should have known that. I always appreciate your time.
In order to use a non-static field, method, or property, you must first create an object of an instance.
HashAlgorithm hashAlgo = HashAlgorithm.Create("SHA512");
Now use the object hashAlgo to call their methods. Reference for more information:
Compiler Error CS0120 | Microsoft Docs[^]
 
Share this answer
 
Comments
Michaelred54 11-Feb-22 7:28am    
Thank you for your comment. This will work as well.
M Imran Ansari 11-Feb-22 7:42am    
Pleasure. Happy Coding!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900