Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .NET CodeDOM to declare and initialize a field in one statement

Tags:

.net

codedom

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.

like image 741
Chris Farmer Avatar asked Jan 25 '23 04:01

Chris Farmer


2 Answers

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.

like image 68
Timothy Fries Avatar answered Jan 29 '23 13:01

Timothy Fries


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();
like image 40
Haacked Avatar answered Jan 29 '23 13:01

Haacked