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?
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:
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());
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With