4

I want to use CodeDOM to both declare and initialize my static field in one statement. How can I do this?

// for example
public static int MyField = 5;

I can seem to figure out how to declare a static field, and I can set its value later, but I can't seem to get the above effect.

@lomaxx, Naw, I just want static. I don't want const. This value can change. I just wanted the simplicity of declaring and init'ing in one fell swoop. As if anything in the codedom world is simple. Every type name is 20+ characters long and you end up building these huge expression trees. Makes my eyes bug out. I'm only alive today thanks to resharper's reformatting.

Chris Farmer
  • 24,974
  • 34
  • 121
  • 164

3 Answers3

8

Once you create your CodeMemberField instance to represent the static field, you can assign the InitExpression property to the expression you want to use to populate the field.

Timothy Fries
  • 2,161
  • 19
  • 8
1

This post by Omer van Kloeten seems to do what you want. Notice that the output has the line:

private static Foo instance = new Foo();
Haacked
  • 58,045
  • 14
  • 90
  • 114
  • Link is dead. Here's a new one: https://msdn.microsoft.com/en-us/library/system.codedom.codememberfield.initexpression(v=vs.110).aspx – makhdumi Jan 23 '17 at 23:32
0

I think what you want is a const rather than static. I assume what you want is the effect of having a static readonly which is why you always want the value to be 5.

In c# consts are treated exactly the same as a readonly static.

From the c# docs:

Even though constants are considered static members, a constant- declaration neither requires nor allows a static modifier.

lomaxx
  • 113,627
  • 57
  • 144
  • 179