I have two classes, the first class Movie
has one attribute string name
. The second class Festival
has also one attribute Movie[] movies
.
The following method which I wrote inside of the class Festival
checks if Movie mv
exists in movies
and returns true
or false
accordingly:
public bool Exist(Movie mv)
{
foreach (Movie movie in movies)
{
if (mv == movie)
{
return true;
}
}
return false;
}
The method works perfectly and returns true
when mv
exists in movies
, and false
when it isn't.
But when I tried to make a function in class Program
named Check
which gets Festival f1
, and Festival f2
and checks if the festivals have a movie in common, the following method always returned false
:
public static bool Check(Festival f1, Festival f2)
{
foreach (Movie movie1 in f1.GetMovies() //returns festival only attributed: movies)
{
foreach (Movie movie2 in f2.GetMovies())
{
if (movie2 == movie1)
{
return true;
}
}
}
return false;
}
So I tried to use the Object.Equals(Object)
method but the following code has also always returned false
:
public static bool Check(Festival f1, Festival f2)
{
foreach (Movie movie1 in f1.GetMovies())
{
foreach (Movie movie2 in f2.GetMovies())
{
if (movie2.Equals(movie1))
{
return true;
}
}
}
return false;
}
The only case I succeeded make it work was when I compared the two objects attribute by using the method GetName()
that returns the name
of the Movie
:
public static bool Check(Festival f1, Festival f2)
{
foreach (Movie movie1 in f1.GetMovies())
{
foreach (Movie movie2 in f2.GetMovies())
{
if (movie2.GetName() == movie1.GetName())
{
return true;
}
}
}
return false;
}
Can someone please explain why the first and last attempts worked, and the other two didn't?