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


here's simplified parts of code have:

abstract class datamanager<tvalue> {     protected static dictionary<string, tvalue> values; } 

and have:

class textmanager : datamanager<string> {     static textmanager()     {         values = ... // fill data     } } 

and, i'm getting ca1810. see few solutions, making values public , setting them elsewhere, don't that, or making static method in textmanager same thing, invoked when program starts, don't either.

i think it's obvious example, values should filled once per tvalue. so, think best solution here?

i turn off rule. thing is, have rule (afaik) designed warn potential performance hit of using static constructor. initialization of static property can done either via static constructor or inline (as suggested msdn). in case can't inline because:

  1. you have actual values in subclass
  2. there's no such thing abstract static method, can't delegate actual inline initialization textmanager.

so leaves static constructor option, means turning off rule (which means "yes, microsoft. know might dangerous performance, know i'm doing").

msdn states: "it safe suppress warning rule if performance not concern; or if global state changes caused static initialization expensive or must guaranteed occur before static method of type called or instance of type created."

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

try (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());     } 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -