简体   繁体   中英

What is equivalent for Java Objects.hash and Objects.hashCode in C#

Moving from Java to C# developer. In Java, I used a lot of Objects.hash(array) and Objects.hashCode(object) to build hash code of an object in hashCode function. I can't find any equivalent for those functions in C#. Any ideas?

Indeed I can call GetHashCode and combine them as shown in Concise way to combine field hashcodes? , but that requires a lot of null checks for reference types and that is making code much longer than comparable Java code.

In Java:

public class MyObject {

    private Integer type;
    private String[] attrs;
    
    @Override
    public int hashCode() {
        int hash = 1, p = 31;
        hash = p * hash + Objects.hashCode(type); // Handle Null case
        hash = p * hash + Objects.hash(attrs); // Handle Null case
        return hash;
    }
}

In C#:

public class MyObject {

    private int? type;
    private string[] attrs;
    
    public override int GetHashCode()
        int hash = 1, p = 31;
        hash = p * hash + hash_of(type);    // Any utilities?
        hash = p * hash + hash_of_array(attrs); // Any utilities?
        return hash;
    }
}

Note: I'm not looking for compatible results (as I know that hash codes would be different for similar objects, and can be different even between versions/platform for the same framework) but rather code size & concise way.

The .NET equivalent of this is the new System.HashCode , in particular the HashCode.Combine<> method which you can use to create a hash code from multiple values:

public class MyObject
{
    private int? type;
    private string[] attrs;

    public override int GetHashCode()
        => HashCode.Combine(type, attrs);

    // remember to also override Equals
}

Note that this type is only available in .NET Core. If you are running on .NET Framework, you will have to implement the hash code calculation yourself. Good ways to do that are documented here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM