Constant vs Readonly in C#

Constant vs Readonly in C#

Difference Between Const and ReadOnly.

One of the most important concepts that we commonly use while writing a C# code . Still there are many developers who do not exactly understand the basic difference between these two and in which case we should go for any of them. Today in this blog I will explain the uses and the difference between them in the most simplest way.

Const and Readonly both of them are the constants both are used to declare the constant values in our programs as shown below.

No alt text provided for this image


Now We will be talking about the difference between the two.

Const is a compile time constant i.e it is processed at the compile time only by the compiler.
Once we set the value of a const field then it is not allowed to change it again.
Once we make any fiend as const we need to assign the value like shown above val1=1000, we cannot leave val1 without assigning any value.
ReadOnly is the Runtime Constant i.e it is processed at Runtime only.
Readonly constant are not forced to assign the value at the compile time.
We can assign value to the readonly fields using the constructor or any config file. As shown below
No alt text provided for this image

In the above Image we can see that Val2 can be assigned or manipulated using the constructor.

So, The time when you are sure about the value that is it going to the same for entire program in any case use CONST, But if there might be a chance that a value could be changed in any scenerio go for ReadOnly.This is all you need to know about the Const and ReadOnly.

Hope Now you have a better clarity for both the concepts.

要查看或添加评论,请登录

ramin azadi的更多文章

  • C# Delegates

    C# Delegates

    Before learning a new subject, I often ask myself some questions to improve my learning process. So, let’s start…

  • How To Read Data From An Excel Sheet

    How To Read Data From An Excel Sheet

    Step 1 Open Visual studio -> New Project -> Console App. Project Name/App Name.

  • C# Dependency Injection — Service Lifetimes

    C# Dependency Injection — Service Lifetimes

    What is Dependency Injection? ASP.NET Core supports the dependency injection (DI) software design pattern, which is a…

  • Thread vs Task in C#

    Thread vs Task in C#

    Thread in C# The Thread class creates an actual operating system level thread in C#. The thread created with the Thread…

  • Var vs Dynamic in C#

    Var vs Dynamic in C#

    Difference between Var and Dynamic. While writing code in C# we have used Var and Dynamic keyword many times but it is…

社区洞察

其他会员也浏览了