I am trying to create a Collection with properties and their respective accessors.
Here is my code:
class SongCollection : List<Song>
{
private string playedCount;
private int totalLength;
public string PlayedCount
{
get
{
foreach (Song s in this)
{
if (s.TimesPlayed > 0)
{
return s.ToString();
}
}
}
}
public int TotalLength
{
get
{
foreach (Song s in this)
{
int total = 0;
total += s.LengthInSeconds;
}
return total;
}
}
}
I’m receiving the error at the “get” point. It tells me that not all code paths return a value… What exactly does this mean, and what am I missing?
Firstly, the reason you’re getting that message is that if
thisis empty, then the code within theforeachblock (which is where the requiredreturnstatement is) would never be executed.However, your
TotalLength()function would always return the length of the firstSong, as you’re declaring your variable, setting its value, then returning it within theforeachblock. Instead, you’d need to do something like this:Your
PlayedCountfunction suffers from similar issues (if the collection is empty or contains no elements whoseTimesPlayedproperty is greater than 0, then there would be no way for it to return a value), so judging by your comment you could write it this way: