- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Difference between readonly and const keyword in C#
readonly keyword
readonly keyword is used to define a variable which can be assigned once after declaration either during declaration or in constructor. const keyword is used to define a constant to be used in the program. Following is the valid usage of a readonly and const keywords in C#.
Example
using System.IO; using System; public class Program { public const int VALUE = 10; public readonly int value1; Program(int value){ value1 = value; } public static void Main() { Console.WriteLine(VALUE); Program p1 = new Program(11); Console.WriteLine(p1.value1); } }
Output
10 11
Following are some of the important differences between readonly and const keywords.
Sr. No. | Key | readonly keyword | const keyword |
---|---|---|---|
1 | Purpose | readonly keyword is used to create a readonly fields. | const keyword is used to create constant fields. |
2 | Type | readonly is a constant defined at runtime. | const is used to create a constant at compile time. |
3 | Change | readonly field value can be changed after declaration. | const field value cannot be changed after declaration. |
4 | Method | readonly fields cannot be defined within a method. | const fields can be declared within a method. |
5 | Value assignment | readonly variables are declared as instance variable and assigned values in constructor. | const fields are to be assigned at the time of declaration. |
- Related Articles
- Explain the difference between const and readonly keywords in C#
- What is the difference between keywords const and readonly in C#?
- What is the difference between #define and const Keyword in C++?
- Difference between const int*, const int * const, and int const * in C/C++?
- Difference between const int*, const int * const, and int const * in C
- Const vs Static vs Readonly in C#
- Difference between const char* p, char * const p, and const char * const p in C
- Difference between #define and const in C
- Function overloading and const keyword in C++
- What is the difference between const int*, const int * const, and int const *?
- What is the const Keyword in C++?
- What is difference between int and const int& in C/C++?
- Difference Between Static and Const in JavaScript
- Difference between #define and const in Arduino
- Difference between out and ref keyword in C#

Advertisements