Description
Bug Report Checklist
- Have you provided a full/minimal spec to reproduce the issue?
- Have you validated the input using an OpenAPI validator (example)?
- What's the version of OpenAPI Generator used?
- Have you search for related issues/PRs?
- What's the actual output vs expected output?
- [Optional] Bounty to sponsor the fix (example)
Description
I've tried to use 5.0 beta version of generator, but I think issue exists in previous versions too.
When models are generated, GetHashCode method is overriden and it uses non read only properties to genereate hash:
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
// Suitable nullity checks etc, of course :)
if (Id != null)
hashCode = hashCode * 59 + Id.GetHashCode();
if (Name != null)
hashCode = hashCode * 59 + Name.GetHashCode();
hashCode = hashCode * 59 + Right.GetHashCode();
return hashCode;
}
}
Jetbrains Resharper marks such places with a warning and documentation states:
You can override GetHashCode for immutable reference types. In general, for mutable reference types, you should override GetHashCode only if:
You can compute the hash code from fields that are not mutable; or
You can ensure that the hash code of a mutable object does not change while the object is contained in a collection that relies on its hash code.
Those rules exists because breaking it this might lead to very nasty bugs because of broken for example HashSet state, here is article that goes into details:
https://vkontech.com/gethashcode-pitfalls/
openapi-generator version
5.0 beta, I'm sure it is like that in older versions too.
Command line used for generation
openapi-generator generate -g aspnetcore -i api.yaml -o . -c openapi-generator-config.json --global-property apis --global-property models
Code to reproduce
var distinctPeople = new HashSet<Person>();
var person = new Person{FirstName = "John"};
distinctPeople.Add(person);
person.FirstName = "Peter";
var lookFor = new Person {FirstName = "Peter"};
Console.WriteLine(distinctPeople.Contains(lookFor)); // False
Suggest a fix
I would say if generated models calculate hash from properties, at least I should be able to disable this override.