const are compile time constants where as readonly are runtime constants. Once assigned you cannot change the values assigned to variables declared as const or readonly.
Usage:
Const variable just like their static(shared in VB) counterparts are accessible via Class Names only. They are not accessible via objects.
Readonly variable are instance variable and accessible via objects.
C#
internal sealed class Program { const int iConst =20; readonly int iReadonly; public Program(int iReadonly) { // Readonly variable can be assigned a value from configuration file or database this.iReadonly = iReadonly; } }
Usage:
Program programObject = new Program(); Program.iConst =20; //programObject.iConst =20; Compile time error programObject.iReadonly =20;
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
VB.Net
Friend NotInheritable Class Program Const iConst As Integer = 20 ReadOnly iReadonly As Integer Public Sub New(iReadonly As Integer) ' Readonly variable can be assigned a value from configuration file or database Me.iReadonly = iReadonly End Sub End Class
Usage:
Dim programObject As New Program() Program.iConst = 20 'programObject.iConst =20; Compile time error programObject.iReadonly = 20