C
C#15mo ago
SWEETPONY

✅ strange behavior with dictionary keys

I have following code:
public class UISchemaGenerator
{
private record CacheKey(
Either<CustomFieldSet, CustomField.CustomField> Type,
CultureInfo Culture);

private readonly ConcurrentDictionary<CacheKey, UISchemaSpecification> _cache = new();

public UISchemaSpecification Generate(
Either<CustomFieldSet, CustomField.CustomField> eitherField,
MandatorySecurityScope scope = default,
CultureInfo culture = default)
{
culture ??= CultureInfo.CurrentCulture;

return eitherField.Match(
ifA: cfs => _cache.GetOrAdd(
new CacheKey(cfs, culture),
_ => InternalGenerator(cfs, scope, culture)),
ifB: cf => _cache.GetOrAdd(
new CacheKey(cf, culture),
_ => InternalGenerator(cf, culture)));
}
public class UISchemaGenerator
{
private record CacheKey(
Either<CustomFieldSet, CustomField.CustomField> Type,
CultureInfo Culture);

private readonly ConcurrentDictionary<CacheKey, UISchemaSpecification> _cache = new();

public UISchemaSpecification Generate(
Either<CustomFieldSet, CustomField.CustomField> eitherField,
MandatorySecurityScope scope = default,
CultureInfo culture = default)
{
culture ??= CultureInfo.CurrentCulture;

return eitherField.Match(
ifA: cfs => _cache.GetOrAdd(
new CacheKey(cfs, culture),
_ => InternalGenerator(cfs, scope, culture)),
ifB: cf => _cache.GetOrAdd(
new CacheKey(cf, culture),
_ => InternalGenerator(cf, culture)));
}
CustomField.CustomField is object with some properties problem: if value of one of the properties will change I will not call InternalGenerator, I will use old value from cache but actually property value has changed
4 Replies
Denis
Denis15mo ago
And the properties that change are used as the key for the cache?
SWEETPONY
SWEETPONYOP15mo ago
as you see but it should be another key because it is record type
Denis
Denis15mo ago
I don't understand you, sorry. Having a type as a record doesn't mean anything. A property of a record type can still be mutable. and changing a value which you use as a key in a dictionary is a bad idea. It should be readonly. If, however, you have to modify the key... then you should catch such an operation and remove the old key value pair from the cache, and replace it with a new one if such an operation is common, you should consider using something else as your key something more permanent
SWEETPONY
SWEETPONYOP15mo ago
did you read the code? Actually I don't change keys
Want results from more Discord servers?
Add your server