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.