I am reading a CSV file and I would like to cache the results in an array.
This is my getter/setter:
private RedirectionRule[] RedirectionRules
{
get
{
if (_redirectionRules == null)
{
return new RedirectionRule[MAXLENGTH];
}
return _redirectionRules;
}
set
{
_redirectionRules = value;
}
}
Is this the right approach to an optimal way of caching the results?
I don’t think there’s much point in returning a new array in your getter when
_redirectionRulesisnull. If you set the property in your code that parses the CSV, then it will be cached.In other words, somewhere you should have a function like this to parse the CSV data (as an example, I’ve put it in the
RedirectionRuleclass, but you could have aRedirectionRuleParserclass or something like that depending on your needs):Then, if you have code like this somewhere, you are caching the data:
Elsewhere, where you want to access the data you have cached:
The only thing your example code would accomplish by creating a new
RedirectionRule[MAXLENGTH]array in your property’s getter would be to sneak past theRedirectionRules != nullcheck above, thereby opening up the possibility of accessing data that looks like it’s been cached but really came out of thin air.