No more lies about static fields

When you declare a static field in C# it is not a field per se — it is a tiny getter which initializes the field on first read. I don’t like this approach because it misinforms the user — user wants a direct access but instead she or he gets a wrapper function. Small lie but still a lie. Initializing all static fields eagerly, even unused, is also not a good idea. So I tried to combine those two in a meaningful way…

Static fields can be initialized only with basic values and the initialization is done eagerly (plain old Int static field with initial value 100 is fine). Every other static field is forbidden.

For other types (and complex initial values) properties come to the rescue — properties are initialized lazily with added guards. The message is clear and the safety is guaranteed, in case of circular initialization you will get nice crash (I am not joking, on various occasions I noticed .Net 4.5 keeps working with silently inserted nulls).

Those changes effectively killed static variables so I made temporary exception in sake of testing them — any Int expression is treated as basic value. Another temporary leftovers are static constructors — I am not sure what to do with them, they will be limited to linear initialization or completely removed.

Full solution will take more time — sure bet are lazy types. With lazy types the notion for user is straightforward thus they could be used for all static fields. The other solution could be allowing function and namespace properties.

Tagged , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: