Difference Between Const,read Only and Static
C# Const makes fields or locals constant.ReadOnly applies to fields in C#, value is abiding after initialization.Static ReadOnly makes ReadOnly field class member.(Can be accessed through class name)
Please go through the summary of differences between const and readonly then I will try to explain each point subsequently that.
Table of Contents
Const vs Readonly in C#:
Const | Readonly |
---|---|
const keyword can be applied to fields or local variables | readonly keyword applies but to fields non local variables |
We must assign const field at the time of declation only | Nosotros can assign readonly field at the time of declaration or in constructor,not in whatever other methods. |
No Memory Allocated Because const value embedded in IL lawmaking itself after compilation | dynamic memory allocated for readonly fields and we tin can get the value at run fourth dimension. |
Const in C# are by default static.Can be accessed only through form proper name | Readonly belongs to the object created so accessed through only through example of course. To make it form fellow member we demand to add together static keyword before readonly. |
We can declare following built in (archaic types) datatypes as const Boolean,Char, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal and also string. | Same as Const |
The value is constant (as information technology is belongs to class) | The value may exist different depending upon constructor used (equally it belongs to object of the grade) |
If we want to declare const for someclass (non-primitive types) nosotros should assign it to null which as of no use. | If you declare a non-primitive types (reference type) as readonly only reference is immutable not the object it contains.(come across the example beneath) |
Do not use const field that might alter over the fourth dimension information technology leads to dll version problem (see the case) | As the value obtained at run time there is no dll versioning problem with static readonly fields |
Const field can not be passed every bit ref or out parameter | We can pass readonly field as ref or out parameters in the constructor context. |
C# Const field or local:
We will use keyword "const" to declare Abiding fields or locals in C#.
Whenever y'all are defining a const field its value must exist assigned at the time of declaration itself, later on that we cannot alter its value. Become through the post-obit example to understand it
Public course Programme { const int fieldConstant = 10; //Field static void Main(string[] args) { const int 10 = 10, Y = 50; //Correct //Local Variable const int Z = X + Y; //Correct const int A = X + GettheValue(); // Error } public static int GettheValue() { const int localx=x; return ten; } }
The commencement 2 lines will works without whatever errors considering X,Y,Z field values are evaluated at the fourth dimension of compile fourth dimension itself. Merely in 3rd line nosotros declared a variable 'A' every bit const and trying to evaluate its value at runtime using GettheValue() method.The line volition not execute because const variables must exist assigned at the time of compile time itself.
In the above examplefieldConstantis a field because its direct declared within program grade.
And we can declare local variables as const as shown in to a higher place GetTheValue() method.
The following built in value types tin can be declared as Const: int, long, char, float, double, decimal, bool, byte, brusk, cord variable equally const.
And nosotros can assign non-primitive types to null to define a const.But information technology's useless to declare a const reference type which is assigned to cypher.
const string constantString = "How-do-you-do Iam Constant"; //Right const Programme programme = new Program(); //Error const Program program1 = null; //Right
You lot cannot declare a const variable as static because const fields are considered every bit static members by default.
ReadonlyConstant r1=new ReadonlyConstant();// Please see the below lawmaking for class declaration Console.WriteLine(r1.ynumber); //Error Panel.WriteLine(ReadonlyConstant.ynumber);//Right
As the const variable past default static, yous cannot admission it from the instance of the class. And we cannot pass const values as ref or out params.
C# ReadOnly Field:
We tin can declare fields as Readonly in C# not local variables.
ReadOnly fields tin can exist initialized at the time of declaration or only within the constructor which is called only once at the time of object creation, not in any other method.
public class ReadonlyConstant { public const int numberOfDays = 7; //Field public readonly double PI=3.xiv; //inline intialization public readonly int znumber; public readonly Listing<int> readonlyList; public ReadonlyConstant() { znumber= 50;//Constructor initialization } public ReadonlyConstant(int x) { znumber=100; } public NormalMethod() { //readonly int i=0; This is wrong } }
And the value may be different depending upon the constructor used. i.e., readonly field belongs to object of the class.
Delight read the further article well-nigh readonly field to understand it further.
The curious case of Readonly field in C#
Now nosotros will go through the differences between const and readonly fields, Every bit mentioned in the second point for const fields no memory allocated and the value straight embedded in IL lawmaking. please see the beneath picture of IL code. (Few differences explained in above postal service)
I used resharper tool to come across Intermediate Language(IL) code of above sample program (ReadonlyConstant.cs)
As you can encounter the IL lawmaking of const field numberOfdays value (7) direct embedded into IL code. Where as the readonly field piValue is displayed every bit piValue i.e., the value can be obtained at run fourth dimension.
This leads to versioning trouble.
Versioning problem of the Const field in C#:
I compiled to a higher place sample plan equally a grade library(A) and used it in some other project (in B) every bit a reference. Now see the generated IL code of project B
And Even in project B IL code, the value of const field numberofdays embedded in IL lawmaking. Now the problem is, in the source (in A ReadonlyConstant.cs library) the const field (numberOfdays )value changed to 5 and compiled and generated a new dll.
But this new value of the const field does not affect in projection B until unless we compile the project. After compilation the new const field value will exist embedded in IL code of projection B.
To overcome this problem we will apply static readonly fields.
C# Static Readonly field:
As the readonly field value is different depending upon the constructor used (As explained in the above article). To get in class member (static fellow member) and unique to the class, we will add together static keyword before the variable as shown below.
public class ReadonlyStatic { public static readonly string x = "Hi"; public static readonly string y; public ReadonlyStatic() { //y = "Hello"; This is wrong } static ReadonlyStatic() { y = "How-do-you-do"; } }
Now we tin utilize it as constant across the grade will overcome the dll version problem with const variables.There may be some performance issues just no need to build the destination projection as the value can exist obtained at run time.
As shown in the above instance we tin can assign static readonly fields at the time of proclamation or in static constructor only.
remaining differences I explained in above readonly commodity (equally the post is becoming large I thought of splitting it two)
C# Readonly vs Static Readonly:
Following are the main differences between readonly and static readonly fields in C#.
Readonly in C# | Static Readonly in C# |
---|---|
Can be assigned at the fourth dimension of announcement or constructor | Tin can be assigned at the time of declaration or static constructor |
Value may exist different depending upon the constructor used | Value will be abiding afterward the initialization |
When to use Const and When to use readonly in C#
Apply const when the value is absolute constant that won't alter over the time. For example Number of days in a week is 7. This is e'er constant. and when in doubt use static readonly to avoid the dll versioning trouble.
As the const field value embedded inside IL. Use const modifier for absolute constants to proceeds performance benefits.
And as explained in the above readonly article if we want to use unlike constant values for a different instance of the grade (or objects) use readonly.
I hope yous sympathize the fundamental differences between const and readonly modifiers in C#.
If so share with your friends and If you have any doubts please experience free to comment below.
Read my manufactures
Understand delegates and events in c#
Difference betwixt Ref and out parameters in C#
Happy Coding….!
Wait before leaving. why tin can't you follow me on twitter or be a friend on Facebook or linkedn to get in touch with me.
Source: https://www.arungudelli.com/tutorial/c-sharp/10-differences-between-constant-vs-readonly-static-readonly-fields/
0 Response to "Difference Between Const,read Only and Static"
Post a Comment