In C#, a readonly keyword is a modifier which is used in the following ways:
1. Readonly Fields: In C#, you are allowed to declare a field using readonly modifier. It indicates that the assignment to the fields is only the part of the declaration or in a constructor to the same class. Such types of fields can only be assigned or reassigned multiple times only at the declaration or in a constructor. They are not assigned after the constructor exit. If the readonly modifier is used with a value type field, then the field is immutable. And if the readonly modifier is used with a reference type field, then the readonly modifier prevents the field from replaced by the different instances of the reference type, here the readonly modifier does not stop the instance data of the field from being modified through the read-only field. In static and instance constructors, you are allowed to pass a readonly field as an out or ref parameter.
Display value of string 1 GeeksforGeeks, and string 2 GFG
Here, the value of the str1 and str2 is assigned in the constructor.
2. Readonly Structure: In the readonly structure, readonly modifier indicates that the given structure is immutable. When you create a readonly structure, it is necessary to use a readonly modifier with its fields, if you do not do this, then the compiler will give an error.
Author name: Rohit Total articles: 67 Branch name: CSE
3. Readonly Members: This feature is introduced in C# 8.0. In this feature, you are allowed to use a readonly modifier to any member of the structure. This readonly modifier specifies that the member is not allowed to modify. It is better than applying the whole structure readonly.
Customer name: Sumit Product: Mobile Phone Price: 2398
- Difference between readonly and const keyword in C#
- Different Types of HTML Helpers in ASP.NET MVC
- Difference Between .NET and ASP.NET Framework
- Difference Between Properties and Indexers in C#
- C# Coding Standards
- C# Program to Convert a Binary String to an Integer
- Basics of FileStream in C#
- C# Program for Nested Conditional Operator
- C# Program for Converting Hexadecimal String to Integer
- Program to Input Weekday Number and Print the Weekday in C#
- What is NuGet?
- Top 10 Programming Languages for Blockchain Development
- C# Program to Convert the Octal String to an Integer Number
- int Keyword in C#
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.