Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a public const Size in C#?

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?

like image 974
BrunoLM Avatar asked Nov 28 '22 10:11

BrunoLM


2 Answers

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.

like image 138
Marc Gravell Avatar answered Dec 04 '22 22:12

Marc Gravell


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 };
like image 41
Cody Gray Avatar answered Dec 04 '22 20:12

Cody Gray