c# - Setting property of dictionary type works in constructor but not when using property default -


this question has answer here:

i have class has property of type dictionary<object, func<object, treenode>>. can happily set property constructor (or using expression body), not default value of property (it doesn't change if property readonly, or have public get/set). issue occurs if dictionary instead stored in field.

it comes error saying cannot access non-static method 'methodname' in static context.

this code fails:

public class treeviewbuilder {     public dictionary<type, func<object, treenode>> objecttreenodebuilder { get; set; }         = new dictionary<type, func<object, treenode>>     {         {typeof(type1), t => buildtype1treenode((type1) t)},         {typeof(type2), t => buildtype2treenode((type2) t)},     };      public treenode buildtype1treenode(type1 type1)     {         return new treenode { tag = type1 };     }      public treenode buildtype2treenode(type2 type2)     {         return new treenode { tag = type2 };     } } 

but code fine:

public class treeviewbuilder {     public dictionary<type, func<object, treenode>> objecttreenodebuilder { get; set; }      public treeviewbuilder()     {         objecttreenodebuilder = new dictionary<type, func<object, treenode>>         {             {typeof(type1), t => buildtype1treenode((type1) t)},             {typeof(type2), t => buildtype2treenode((type2) t)},         };     }      public treenode buildtype1treenode(type1 type1)     {         return new treenode { tag = type1 };     }      public treenode buildtype2treenode(type2 type2)     {         return new treenode { tag = type2 };     } } 

i'm guessing objecttreenodebuilder property being initialised before treeviewbuilder object instantiated/constructed, therefore methods aren't yet known about; , why complains methods should static. correct, or else going on under hood?

the compiler creating static constructor set default value property. error message indicates, non-static methods not accessible static constructor.


Comments

Popular posts from this blog

amazon web services - S3 Pre-signed POST validate file type? -

c# - Check Keyboard Input Winforms -