How to hash a string in C#

1 Answer

0 votes
using System;

class Program
{
    /// <summary>
    /// Computes a hash value for a string.
    ///
    /// String.GetHashCode() is the built-in hash function
    /// provided by .NET and Mono.
    ///
    /// Important:
    /// - Equal strings produce the same hash value.
    /// - Different strings may produce the same hash value
    ///   (called a collision).
    /// - Hashes are useful for fast lookups in collections
    ///   such as Dictionary and HashSet.
    /// - Hashes are not encryption and cannot be reversed.
    /// </summary>
    /// <param name="text">The string to hash.</param>
    /// <returns>A 32-bit integer hash value.</returns>
    static int HashString(string text)
    {
        if (text == null) {
            throw new ArgumentNullException("text");
        }

        return text.GetHashCode();
    }

    static void Main()
    {
        // Example input string.
        string text = "Hello, World!";

        // Compute the hash value.
        int hashValue = HashString(text);

        Console.WriteLine("Original string: " + text);
        Console.WriteLine("Hash value     : " + hashValue);
        Console.WriteLine();

        /*
         * Compare two strings using their hashes.
         *
         * Comparing integers is usually faster than
         * comparing long strings character by character.
         */
        string anotherText = "Hello, World!";

        int hash1 = HashString(text);
        int hash2 = HashString(anotherText);

        if (hash1 == hash2)
        {
            Console.WriteLine("Hashes match.");

            /*
             * IMPORTANT:
             *
             * Matching hashes do not guarantee that
             * the strings are equal.
             *
             * Two different strings can sometimes
             * produce the same hash value.
             *
             * Therefore, always compare the original
             * strings when exact equality is required.
             */
            if (text.Equals(anotherText)) {
                Console.WriteLine("Strings are identical.");
            }
            else {
                Console.WriteLine("Hash collision detected.");
            }
        }
    }
}



/*
run:

Original string: Hello, World!
Hash value     : 630197767

Hashes match.
Strings are identical.

*/

 



answered Oct 4 by avibootz
...