C
C#5w ago
Tofaa

Dictionary<> Keys do not get fetched properly

private readonly Dictionary<NamespacedKey, Texture2D> _textures = new();

internal void Load() {
var path = "assets/textures";
var files = Directory.GetFiles(path);
foreach (var file in files) {
var texture = Raylib.LoadTexture(file);
var id = NamespacedKey.texture(file.Replace("assets/textures\\", "").Replace(".png", ""));
_textures.Add(id, texture);
Console.WriteLine("Loaded texture with id " + id.Full + " Texture Format:" + texture.Format);
}
}

internal void Unload() {
foreach (var texture in _textures) {
Raylib.UnloadTexture(texture.Value);
}
}
private readonly Dictionary<NamespacedKey, Texture2D> _textures = new();

internal void Load() {
var path = "assets/textures";
var files = Directory.GetFiles(path);
foreach (var file in files) {
var texture = Raylib.LoadTexture(file);
var id = NamespacedKey.texture(file.Replace("assets/textures\\", "").Replace(".png", ""));
_textures.Add(id, texture);
Console.WriteLine("Loaded texture with id " + id.Full + " Texture Format:" + texture.Format);
}
}

internal void Unload() {
foreach (var texture in _textures) {
Raylib.UnloadTexture(texture.Value);
}
}
NamespacedKey is just a class that stores 3 strings. I override the GetHashCode() method in it to
public override int GetHashCode()
{
return Domain.GetHashCode() + Key.GetHashCode() + Family.GetHashCode();
}
public override int GetHashCode()
{
return Domain.GetHashCode() + Key.GetHashCode() + Family.GetHashCode();
}
Ive tried different hashcodes incase im just stupid but nothing works
7 Replies
Tofaa
TofaaOP5w ago
using the string of domain + key + family as the key in the dictionary works, but not my own class Okay apparently you need to override the equals function for some reason? I'd assume it just fetches the key from the hash code alone but it does an equals check aswell?
ero
ero5w ago
indeed it does: https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/Collections/Generic/Dictionary.cs,428 you should pass an EqualityComparer instead of implementing GetHashCode and Equals and if you do implement GetHashCode, use HashCode.Combine
SleepWellPupper
Implementing an EqualityComparer seems unnecessary to me in this case. Tip for OP: in VS you can generate GetHashCode and Equals implementations using the quick actions context menu when opened on the type name (put caret in type name, press ctrl+. then select generate Equals+GetHashCode)
ero
ero4w ago
how do you implementGetHashCode and Equals for byte[]?
SleepWellPupper
Alternatively, if the identity of a NamespaceKey is fully determined by those 3 strings, you should look at records also.
ero
ero4w ago
wrong channel... sorry you're right
SleepWellPupper
Records come with generated Equals/GetHashCode implementations that should fit your needs (from what I can tell frkm your examples)
Want results from more Discord servers?
Add your server