Constant or ReadOnly?

by William O'Grady for Blog
Constant or ReadOnly?

ReadOnly properties and constant fields may seem to achieve the same results. However, there are many differences which must be taken into consideration when choosing which one to use. 

Constant Field 

A constant field can be created in a class for information that is to be hard coded into the application and will not be changed. This often used for mathematical values such as Pi. A constant is considered a “Compile-Time Constant”. This means the values is fully evaluated at compile time. It cannot be assigned to a value returned from a method or an object instance. The compiler compiles the constant value into every reference in the application. If you later change the value of the constant, it will also change value in every location it is used in the code.  

public class Maths 

public const double Pi= 3.14  

A constant must be assigned on declaration. It can only be a number, string or Boolean as these can be evaluated at compile time. 

Must be assigned on declaration 

Can only be a number, Boolean or string as these can be evaluated at compiled time 

They are always static  and can be accessed using the class name as seen below: 

var area = Math.Pi * radius * radius; 

ReadOnly Property 

A Read-Only Property is a variable in a class that is initialised and then not changed again. It is considered a “Runtime Constant”, which means that it can be assigned to any valid expression at runtime.  

The property can be assigned on declaration or in a constructor as seen below: 

In declaration: 

public class Maths { 

public readonly decimal myPrice = GetPrice(); 

In constructor: 

public readonly decimal myPrice; 


public Product(){ 
MyPrice = GetPrice();  } 

By default, a readonly field is not static so you must create an instance of the class in order to call it. 

var newProduct = new Product();

var newPrice = newProduct.myPrice;

Read-Only properties can have any data type and can optionally be static.  

When to use each? 

It is better to use Constants with simple data types and when you can be certain that the values will never change. 

You may use a Read-only property when value is initialised from a code, a file or a table but then cannot be changed anywhere else in the application. If it is to be shared by all instances, then it should be a static read-only field. If the field value could be different for each instance then leave the field as non-static.  

CRM de la CRM
Prev post NoSQL because we made that Prequel

A SQL database is a database that has relational data. For example Phil is in…

CRM de la CRM
Next post CRM de la CRM

The Problem Our client came to us with a problem: they were paying a lot…