I am trying to write the following code:
public const Size ImageSize = new Size() { Width = 28, Height = 28 };
But I get the error that Width
and Height
are read-only.
What is the recommended way to do this?
const
is restricted to primitives that the compiler can directly write as IL directly. readonly
should suffice here if Size
is treated as immutable, i.e.
public static readonly Size ImageSize = new Size(28,28);
Note that if Size
is a mutable struct
, bad things can happen; I would recommend a property rather than a field to prevent a number of confusing side-effects.
The fundamental problem is that you cannot declare an object of type System.Drawing.Size
as const
. That indicates that the symbol is to be replaced at compile-time with the value of the constant.
Instead, you should use readonly
. This is also a "constant" value in the sense that it cannot be modified once the constructor has run, but the objects are created at run-time instead of compile-time.
The following code compiles just fine:
public static readonly Size ImageSize = new Size() { Width = 28, Height = 28 };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With