1.

Constant vs Readonly in C#

Answer»

The const in C# is faster than readonly, but the performance of const is not better than readonly.

  • Const

A value with const KEYWORD cannot change throughout the LIFE of a program.

A const variable cannot be reassigned.

  • Readonly

A value with Readonly keyword whose value can be initialized during runtime, unlike const.

Let us now see the DIFFERENCE:

Basis
ConstReadonly
Local VariableCan be applied to local variables.Cannot be applied to local variables
MemoryMemory is not allocated.Dynamic memory is allocated for readonly fields.
StaticConst are by-default staticTo make it class member, INCLUDE static keyword before readonly
Ref or outWe cannot pass const field as ref or out parameterThe readonly field can be passed as ref or out parameters in the constructor context.
FasterFaster than readonly.Readonly isn’t faster.
PerformancePerformance isn’t better than readonly.Performance is better than const.


Discussion

No Comment Found