Using .NET CodeDOM to declare and initialize a field in a single expression

I want to use CodeDOM to declare and initialize my static field in a single expression. How can i do this?

// for example public static int MyField = 5; 

I can understand how to declare a static field, and I can set its value later, but I cannot get the above effect.

@lomaxx, Well, I just want a static one. I do not want const. This value may change. I just wanted simplicity to declare and start in one fell swoop. It’s as if something in the encoded world is simple. Each type name is 20 characters long and you create these huge expression trees. Makes my eyes make mistakes. I'm only alive today thanks to reformatting reformatting.

+4
source share
3 answers

After creating an instance of CodeMemberField to represent the static field, you can assign the Expression property you want to use to the InitExpression property to fill the field.

+8
source

This post by Omer van Cloethen seems to be doing what you want. Note that the output has a line:

 private static Foo instance = new Foo(); 
+1
source

I think what you want is const rather than static. I assume you want the static effect readonly, so you always want the value to be 5.

In C #, consts are handled exactly the same as static static.

From C # docs :

Despite the fact that constants are considered static members, the declaration neither requires nor allows the use of a static modifier.

0
source

Source: https://habr.com/ru/post/1276444/


All Articles