- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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. |
Advertisements