- 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
What are the benefits to marking a field as readonly in C#?
The readonly keyword is used to declare a member variable a constant, but allows the value to be calculated at runtime. This differs from a constant declared with the const modifier, which must have its value set at compile time. Using readonly you can set the value of the field either in the declaration, or in the constructor of the object that the field is a member of.
The 'readonly' modifier can be used in a total of four contexts:
Field declaration
Readonly struct declaration
Readonly member definition
Ref read only method return
When we use the field declaration context, we need to know that the only time the assignment can occur is when it is declared or when the constructor of the same class is invoked.
Example
class Program{ readonly string Name; public Program(){ Name = "Name"; } static void Main(string[] args){ Program a = new Program(); System.Console.WriteLine(a.Name); Console.ReadLine(); } }
Output
Name
readOnly Struct
public readonly struct Server{ public readonly string Name; public Server(string name){ Name = name; } } class Program{ static void Main(string[] args){ Server a = new Server("Domain Controller"); System.Console.WriteLine(a.Name); Console.ReadLine(); } }
Output
Domain Controller
Advertisements