Exploring the online world is my passion. have experience of #content writing #SEO #Digital Marketing #On-Page #Lead Generation #Content Analyst #Marketing Analyst... I could never stop at one point, continuously wanted to acquire more and more skills. My work for any organization will be full of passion and hard work.
Thedifferenceis that the value of a staticreadonlyfield is set at run time, so it can have a different value for different executions of the program. However, the value of aconstantfield is set to a compile timeconstant. Read-onlyvariables will be initialized only from the Static constructor of the class.
Initialization of readonly field was not compulsory but in constant it’s compulsory.
Readonly field accessed by object reference and constant accessed by class name.
The value of readonly property can be change, but constant value will be fixed.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Learn { publicclassConstant_Vs_Readonly { publicconstint CONSTANT_INPUT = 2; publicreadonlyint ReadOnly_Input = 10; public Constant_Vs_Readonly() { ReadOnly_Input = 4; } staticvoid Main(string[] args) { Constant_Vs_Readonly obj = newConstant_Vs_Readonly(); Console.WriteLine(obj.ReadOnly_Input+ "" + Constant_Vs_Readonly.CONSTANT_INPUT); Console.ReadLine(); } } }
Liked By
Write Answer
What is Difference between Constant and ReadOnly Property?
Join MindStick Community
You have need login or register for voting of answers or question.
Hemant Patel
02-Mar-2017The difference is that the value of a static readonly field is set at run time, so it can have a different value for different executions of the program. However, the value of a constant field is set to a compile time constant. Read-only variables will be initialized only from the Static constructor of the class.
Initialization of readonly field was not compulsory but in constant it’s compulsory.
Readonly field accessed by object reference and constant accessed by class name.
The value of readonly property can be change, but constant value will be fixed.