Persistent and readonly in C #?

Possible duplicate:
What is the difference between constant and readonly?

I have doubts in C # what the difference is in the constant and readonly explain with a simple problem or any link.

+1
source share
8 answers

A is constinitialized at compile time and cannot be changed.

A is readonlyinitialized at run time, but can only be executed once (in the constructor or in the built-in declaration).

+12
source

const - : , , . , , , . readonly, const, :

class Foo {
  int makeSix() { return 2 * 3; }
  const int const_six = makeSix(); // <--- does not compile: not initialised to a constant
  readonly int readonly_six = makeSix(); // compiles fine
}

A readonly , , . readonly , .

, : , , . :

class Foo {
  readonly List<string> canStillAddStrings = new List<string>();

  void AddString(string toAdd) {
    canStillAddStrings.Add(toAdd);
  }
}

:

class Foo {
  readonly List<string> canStillAddStrings = new List<string>();

  void SetStrings(List<string> newList) {
    canStillAddStrings = newList; // <--- does not compile, assignment to readonly field
  }
}
+4

(const) .

readonly ( ) , .

+3

A const , .

A readonly , .

+2

const , const 1, 2, 1 const. readonly, .

+2

constast are initialized at runtime and can be used as static elements. readonly can be initialized at run time and only once.

+1
source

In C #, constant members must be assigned values ​​at compile time. But you can only initialize readonly members at runtime.

0
source

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


All Articles