Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix "CA1810: Initialize reference type static fields inline" with an abstract base...?

Here's the simplified parts of code that I have:

abstract class DataManager<TValue>
{
    protected static Dictionary<string, TValue> Values;
}

and then I have:

class TextManager : DataManager<string>
{
    static TextManager()
    {
        Values = ... // Fill with data
    }
}

And, now I'm getting CA1810. I see a few solutions, like making Values public and setting them elsewhere, but I don't like that, or making a static method in TextManager to do the same thing, but is invoked when the program starts, but I don't like that either.

I think it's obvious from the example, the Values should only be filled once per TValue. So, what do you think would be the best solution here?

like image 225
avance70 Avatar asked Feb 23 '11 11:02

avance70


1 Answers

I would turn off the rule. The thing is, you have a rule that (AFAIK) is designed to warn you about the potential performance hit of using a static constructor. I would say that initialization of a static property can be done either via a static constructor or inline (as suggested by MSDN). In your case you can't do it inline because:

  1. you only have the actual values in the subclass
  2. there's no such thing as an abstract static method, so you can't delegate the actual inline initialization to TextManager.

So that leaves the static constructor option, which basically means turning off the rule (which means "yes, Microsoft. I know this might be dangerous for performance, but I know what I'm doing").

MSDN states: "It is safe to suppress a warning from this rule if performance is not a concern; or if global state changes that are caused by static initialization are expensive or must be guaranteed to occur before a static method of the type is called or an instance of the type is created."

=======================================================================

Try this (warning: tested on Mono 2.6.7, not .NET):

abstract class DataManager<TValue>
{
    protected static Dictionary<string, TValue> Values=new Dictionary<string, TValue>();
}

class TextManager : DataManager<string>
{
    static TextManager()
    {
        Values.Add("test","test");
    }

    public static string test()
    {
        return Values["test"];
    }
}

class IntManager : DataManager<int>
{
    static IntManager()
    {
        Values.Add("test",1);
    }

    public static int test()
    {
        return Values["test"];
    }   
}

public static void Main (string[] args)
{
    Console.WriteLine(IntManager.test());    
    Console.WriteLine(TextManager.test());    
}
like image 197
Paolo Falabella Avatar answered Oct 30 '22 22:10

Paolo Falabella