I have a City class and inside that a Detail class:
public class City {
public string PartitionKey { get; set; }
public string RowKey { get; set; }
public string Notes { get; set; }
public class Detail
{
public Detail()
{
ImageFile = String.Empty;
Explanation = new HtmlText();
}
public string ImageFile { get; set; }
public HtmlText Explanation { get; set; }
}
}
In my code I have some lines that check how many details there are and if there are less than ten then I add new City.Details. I am using the code below to do this but it’s located in a few different methods and does not look clean. Is there some way that I could simplify this and also add the logic of checking, counting and adding into my base City class?
foreach (int index in Enumerable.Range(0, 10 - vm.Details.Count()))
{
vm.Details.Add(new City.Detail());
}
As the others said, use something like the following
or even a regular for construct
Otherwise when other people read your code (or you look at it 3 months from now) the reaction is going to be “huh?” instead of just automatically recognizing what’s happening.
Here are three ways to address the problem:
1) Just add ten Details to the City object when you create it, use those and then create more if/when necessary
2) Why do you need 10 Details if there aren’t really 10 Details? As much as possible it’s best to have your objects truly represent what they are… representing. So perhaps you are trying to fix what is just a symptom of a deeper problem. But if that’s not the case, then…
3) As the others have mentioned just move this logic into your base class.
Edit: I should have also made clear on #3 that you need a way to make this process automatic so you don’t have to explicitly call the procedure that pads it with extra Details. I don’t have enough info from your code to know how exactly to tell you to do this but if you want to provide more info as to why it’s important to have 10 Details then I’m sure I could help further.