Net-informations.com

Const Vs readonly in C#

Declaration and Initialization

  1. A constant member is defined at compile time and cannot be changed at runtime.
  1. A readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared.

Or

Practical Difference between Const & ReadOnly
  1. A readonly field can have different values depending on the constructor used.

  2. A readonly field can also be used for runtime constants.

Static keyword

  1. Constants are accessed as if they were static fields, although they cannot use the static keyword.

  2. A readonly member is not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.

Memory Allocation

Difference between const and readonly in C#.NET
  1. No Memory Allocated, because const value is embedded in IL code itself after compilation.

  2. Dynamic memory allocated for readonly fields and we can get the value at run time.

ref or out

  1. Const field can not be passed as ref or out parameter
  2. readonly field can be pass as ref or out parameters in the constructor context.

Evaluation

  1. The value of constant is evaluated at compile time
  2. The value of readonly is evaluated at run time

Objects

  1. The value is constant for all objects
  2. The value may be different depending upon constructor used (as it belongs to object of the class)

Const and Read-Only in C# with Examples









net-informations.com (C) 2020    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.
SiteMap  | Terms  | About