1

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?

Ariel Oz
  • 11
  • 2

1 Answers1

0

I will catch all snippets by order.

First snip, i guess movies object is a global variable and you pass movie as member of collection - Exist(movies[0]), that`s working, because reference the same, if you try to create custom object with field value, that present in list - it will return false.

Next, you can't use Object.Equals for checking your custom objects, you need to override it, there you can see how to do it. In a row you tried to do movie2 == movie1. That`s didn't work with the same reason - you didn't override == operator. There is an explanation

The last one is working proper way, because it`s checking real data, names of your movies, which makes sence

Red Star
  • 556
  • 3
  • 13