I have a class, which I'll refer to as SpiderNest
, that has a property of type List<Spider>
, where Spider
is a type of object with a property that is of type int
; we'll call this property NumberOfLegs
. I want either a method or property on the SpiderNest
class to get the sum of the number of legs for all the spiders in my nest.
Would it be preferred to use a property like this (forgive poor object naming):
class SpiderNest {
// Our example property.
public List<Spider> Spiders { get; set; }
public int TotalLegNumber
{
get { return Spiders.Sum(spider => spider.NumberOfLegs); }
}
Or a method?
class SpiderNest {
public List<Spider> Spiders { get; set; }
public int GetTotalNumberOfLegs()
{
return Spiders.Sum(spider => spider.NumberOfLegs);
}
}
And why would you choose that way? I know the question may be finicky but whenever I'm presented with two ways of doing something, there's usually benefits to each way of doing things. Thanks SO!