Alxandr / SpotiFire

A project to make a SpotifyClient in C#
http://nudoc.azurewebsites.net/SpotiFire
40 stars 19 forks source link

Override ==, !=, Equals and GetHashCode in all the SpotifyTypes. #30

Closed Alxandr closed 11 years ago

Alxandr commented 11 years ago

Equality in SpotiFire should be handled explicitly. This is a lot of copy-pasting, and is written here to be done later (or by somebody else). The spesifications are as following:

ChrisBrandhorst commented 11 years ago

Well, tonight I implemented all of them, but it's not working completely yet. Suppose I have the following code:

// playlist.cpp

int Playlist::GetHashCode() {
    SPLock lock;
    return (new IntPtr(_ptr))->GetHashCode();
}

bool Playlist::Equals(Object^ other) {
    SPLock lock;
    return other != nullptr && GetType() == other->GetType() && GetHashCode() == other->GetHashCode();
}

bool SpotiFire::operator== (Playlist^ left, Playlist^ right) {
    SPLock lock;
    return Object::ReferenceEquals(left, right) || (!Object::ReferenceEquals(left, nullptr) && left->Equals(right));
}

bool SpotiFire::operator!= (Playlist^ left, Playlist^ right) {
    SPLock lock;
    return !(left == right);
}
// playlist.h

// Member functions
virtual int GetHashCode() override;
virtual bool Equals(Object^ other) override;

// Non-member functions
bool operator== (const Playlist^ left, const Playlist^ right);
bool operator!= (Playlist^ left, Playlist^ right);

From the C# code, Equals() works correctly, but the == operator does not. Setting a breakpoint in it reveals that it isn't called at all. You know what I am missing? I read that you actually should do operator== (const Playlist^ left, const Playlist^ right), but Object::ReferenceEquals won't take const parameters. Related?

Alxandr commented 11 years ago

Actually, what I tend to do in these cases is decompile the compiled C++ using Telerik JustDecompile (it's free) to see what the compiler made C# wize.

Also, I'm ugessing this is the root of your problem: http://stackoverflow.com/questions/12212243/c-cli-overloaded-operator-is-not-accessed-via-c-sharp

ChrisBrandhorst commented 11 years ago

Thanks for the pointers (pun!!!! ahum...). I guess Google was not my friend yesterday. Will try it tonight.

ChrisBrandhorst commented 11 years ago

BTW, I guess I can leave out the SPLock lock; lines, since no libspotify calls are made?

Alxandr commented 11 years ago

Yeah. SPLock is only for libspotify-calls. I've created a separate ObjLock (lately, probably not in master yet) that can be used whould the need arise to lock on anything else.