C
C#2y ago
Xellez

Dictionary Implementation, but with custom class as key

I have implemented a dictionary like this code file Now Dictionary.Add(10, "Washington"); will work, but what if I want the key to be the latitude and longitude of the city?
public class GeoLocation
{
private float _latitude, _longitude;

public GeoLocation(float latitude, float longitude) {
_latitude = latitude;
_longitude= longitude;
}
}
public class GeoLocation
{
private float _latitude, _longitude;

public GeoLocation(float latitude, float longitude) {
_latitude = latitude;
_longitude= longitude;
}
}
can I pass my class as my key or do I need to adjust my dictclass ?
6 Replies
Angius
Angius2y ago
If you make your GeoLocation class a struct or a record, pretty sure it will just work as the key Since they use value equality That way, no need to reimplement a Dictionary
Xellez
XellezOP2y ago
so it would be something like this
var P1 = new GeoLocation (0, 0);
var Dictionary = new Dict<P1, string>();
var P1 = new GeoLocation (0, 0);
var Dictionary = new Dict<P1, string>();
Angius
Angius2y ago
No
var dict = new Dictionary<GeoLocation, string>() {
[new GeoLocation(12, 78)] = "Paris",
[new GeoLocation(98, -18)] = "Frankfurt"
};
var dict = new Dictionary<GeoLocation, string>() {
[new GeoLocation(12, 78)] = "Paris",
[new GeoLocation(98, -18)] = "Frankfurt"
};
Xellez
XellezOP2y ago
hm this is for the System.Collections.Generic Dictionary right? I am using my own dictionary implementation so if it is giving me Cannot apply indexing with [] to an expression of type 'Dict<GeoLocation, string> does it mean I screwed-up in my implementation ?
Angius
Angius2y ago
Yes, for the regular dictionary I see no point implementing your own tbh
Xellez
XellezOP2y ago
well it is for an exercise I am trying to solve
The focus of this exercise is the use of generics, and the understanding of interfaces and interface inheritance by implementing and using your own class(es).
this is their reason for it so what am I supposed to do for it to work with my implementation using struct?
Want results from more Discord servers?
Add your server