Compile Time Consants

I am creating modules for communicating over I2C with some motor drivers using a G30 and NETMF 4.3.

In order to speed up future developement I was thinking I would create modules which defined everything that could possibly be written to the device in a programmer friendly way.

IE instead of having to keep referring to the data sheets and binary to hex/decimal calculators to make I2C transactions by building byte arrays with the correct values I would want to instead do something like

byte[] TransactionData = new byte[] { A_REGISTERS_ADDRESS, DEFAULT | MY_OPTIONS_FOR_BITS_4_THRU_1 | MY_OPTION_FOR_BIT_0)

My question is if there is a way for me to be sure that any such assignment is evaluated as the IL is created?

So that I don’t waste memory on options or addresses that I don’t end up using.

Basically like compile time constants that I would use to accomplish this in C.

ORing, shifting, adding, or whatever you do with constants is automatically calculated at compile time. It uses no system resources.

1 Like

Thanks, Gus. This gives me the confidence to go ahead with the plan and then I’ll check the IL to see what I get.

Regarding your example, keep in mind that this array will be allocated (i.e. put on the heap). So while the use of constants (declared with const) will be compiled into IL, the array will not. It will be created when the ‘new’ is reached in the method (or, in case of a field initializer, at the time the class is loaded).

1 Like

Hmm, this makes me wonder then if I should ditch enums altogether in place of bytes I can declare with the const keyword. I read that enums are desired when using values as flags, IE using them in bitwise combinations. I haven’t had the opportunity to explore the IL yet.

Actually, values declared in enums are pretty much just const ints. I find them perfect for grouping constant values just like in your case.

Edit: Oh, and by the way you can define your enum MyConstants : byte { ... } in order to handle them as byte values. Storage wise I am not sure, I suspect it might not make a difference because I could imagine that IL literals are always at least 4 bytes wide.

1 Like