Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C# ASP.NET MVC Basics Modeling and Presenting Data Adding Repository Methods

Aaron Selonke
Aaron Selonke
10,323 Points

Why the empty (null) ComicBook variable?

The method checks each of the three comic books in the array to see which ComicBook object matches the id paramter given to the GetComicBook Method. OK.

public ComicBook GetComicBook(int id)
        {
            ComicBook comicBookToReturn = null;

            foreach (var comicbook in _comicBooks)
            {
                if (comicbook.ID == id)
                {
                    comicBookToReturn = comicbook;
                    break;
                }
            }


            return comicBookToReturn;
        }

We do we need the ComicBookToReturn variable?

Why not just do this:

public ComicBook GetComicBook(int id)
        {
            foreach (var comicbook in _comicBooks)
            {
                if (comicbook.ID == id)
                {
                    return comicbook;
                    break;
                }
             }
           }

I'm sure that there is a good reason for the variable, but I'm not sure what it is..

Thanks

2 Answers

Hi Aaron,

The way your method is written, it doesn't leave any return option for "no such comic book exists". All code paths have to return a value when you specify a type of result to return (in this case, ComicBook). Even if that value is null.

If you really want to get rid of that variable, you could add a "return null" statement outside the foreach loop. You'd also want to get rid of your "break", because the return statement will break the loop once it becomes true, so "break" would never actually be read.

Hope that helps!

James Churchill
STAFF
James Churchill
Treehouse Teacher

Great question Aaron! I agree with Evan's thoughts and would add the following...

Some developers would consider it bad form to have multiple "return" statements. Having multiple "return" statements can sometimes make it difficult to understand the control flow of a method. That being said, the method in this case is relatively short, so that's probably not much of an issue.

Having the "comicBookToReturn" variable also makes it incrementally easier to debug the method. We can set a breakpoint on the "return" statement and easily evaluate the value of the "comicBookToReturn" variable.