0

I am creating a class (let's call it listClass) that provides a number of lists that get pulled from the database and cached for future use. One of these is to return a list of Regions for a given Country. I currently have it built as a method:

public static List<string> Regions(string country)
{
    List<string> regions;
    string cacheKey = "CachedRegions_" + country;
    // try to get regions from cache

    if (regions == null)
    {
        // load regions from database
        // cache regions
    }

    return regions;
}

It is currently accessed thusly:

List<string> myRegions = listClass.Regions(myCountry);

However, as what I am accessing is much closer to a property than a method (and every other list in the class is a property), I feel it would be more appropriate to be able to access it like so:

List<string> myRegions = listClass.Regions[myCountry];

Note that I want to be able to cache the Regions for each Country separately (so I'm not caching/loading every region in the world each time I touch the property). Is there a way to create Regions as a property (that can be accessed via a key) rather than as a method?

snumpy
  • 2,808
  • 6
  • 24
  • 39
  • 2
    That's called an [indexed property](https://msdn.microsoft.com/en-us/library/aa288464(v=vs.71).aspx). [You can't make them static though](http://stackoverflow.com/questions/154489/are-static-indexers-not-supported-in-c), if that is your question. – CodeCaster Nov 05 '15 at 15:30

1 Answers1

1

Well, it's possible but it would require you to make Regions a property, and change the type of Regions to a structure that can be indexed by a string and returns a List<string>. Similar to a Dictionary<string, List<string>>, but with the additional logic in that type to load the data from a data source.

Rather than going through all of that, my opinion is it would be simpler just to change the name of the method to

public static List<string> GetRegions(string country) 

That way it "feels" less like a property and you're out of the dilemma you're in. If you have other technical reasons for wanting to access it like an indexer then that may change things.

I want to be able to cache the Regions for each Country separately

Sure. You can still add caching in the method if you want. Or add it to this new class that you would create.

D Stanley
  • 149,601
  • 11
  • 178
  • 240