How to create an open 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 an error that Widthand Heightare read-only.

What is the recommended way to do this?

+3
source share
7 answers

constlimited to primitives that the compiler can directly write as IL directly. readonlyshould be here if Size considered unchanged, i.e.

public static readonly Size ImageSize = new Size(28,28);

Note that if it Sizeis mutable struct, bad things can happen; I would recommend a property rather than a field to prevent a number of confusing side effects.

+7
source

, System.Drawing.Size const. , .

readonly. "" , , , .

:

public static readonly Size ImageSize = new Size() { Width = 28, Height = 28 };
+10
public static readonly Size ImageSize = new Size(28,28);
+1

:

public readonly Size ImageSize = new Size(28, 28);

, , .

:

- , . null.

+1

, :

public const Size ImageSize = new Size() { Width = 28, Height = 28 };

:

public const Size ImageSize = new Size();
ImageSize.Width = 28;
ImageSize.Height = 28;

, , , . . , , const , .

, , const. , , - . readonly. .

Size , , ?

+1

, . , . Size ( , ). (, System.Drawing.Size), readonly const.

0

You can use:

public static readonly Size ImageSize = new Size(28, 28);

This is not actually const, but after initialization it will not be changed.

0
source

Source: https://habr.com/ru/post/1793861/


All Articles