0

Possible Duplicate:
Creating a constant Dictionary in C#

I currently have:

    public string GetRefStat(int pk) {
        return RefStat[pk];
    }
    private readonly Dictionary<int, int> RefStat =
    new Dictionary<int, int> 
    {
        {1,2},
        {2,3},
        {3,5} 
    };

This works but the only time I use the RefStat dictionary is when it is called by GetRefStat.

Is there a way I can combine the method and the dictionary?

Community
  • 1
  • 1
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427

3 Answers3

0

Yes, you can init the dictionary in the type's constructor. You can then change method GetRefStat to a property. So the meta code may look like this

class Foo
{
    public Dictionary<int, int> RefStat {get;private set;}

    Foo()
    {
        RefStat = new Dictionary<int, int> 
        {
            {1,2},
            {2,3},
            {3,5} 
        };
    }
}

And usage

Foo f = new Foo();
var item = f.RefStat[0] 
oleksii
  • 35,458
  • 16
  • 93
  • 163
0

Well you can make an extension method and then all dictionaries can use the function. I am going to assume that GetRefStat will be more than simply grabbing a value from a dictionary with a key:

public static class DictionaryExtensions
{
    public static TValue GetRefStat<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key) 
    {
        return dictionary[key];
    }
}

Then all dictionaries can call it like:

var dictionary = new Dictionary<int, int> 
    {
        {1,2},
        {2,3},
        {3,5} 
    };
var value = dictionary.GetRefStat(2)

If this dictionary is a bunch of constants then this answer is overkill. Just use if/else or switch.

John Kalberer
  • 5,690
  • 1
  • 23
  • 27
0

Something like this?

 public string GetRefStat(int pk) 
{ 
    return new Dictionary<int, int>   
    {  
        {1,2},  
        {2,3},  
        {3,5}   
    }[pk]; 
} 
Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38
  • Creating a new dictionary object for every lookup is a terrible idea. – Asti Sep 14 '12 at 16:47
  • It is typical for such functions to be called once for type instance. So it can be not so terrible as you think. – Kirill Bestemyanov Sep 14 '12 at 19:23
  • Typical? The OP wanted a compile-time defined mapping between a set of numbers. You're wasting cycles with object instantiation, hashing, creating buckets and garbage collection. – Asti Sep 14 '12 at 20:11