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#
- Automation Using Selenium in C# With Example
- How to Execute C# Program on cmd (command-line)?
- How to Install and Setup Visual Studio for C#?
- What is .NET 3-Tier Architecture?
- Cross Join in LINQ
- Comparing two ValueTuple<T1, T2, T3, T4, T5, T6, T7, TRest> in C#
- Compare two ValueTuple<T1, T2, T3, T4, T5, T6, T7> in C#
- Comparing two ValueTuple<T1, T2, T3, T4, T5, T6> in C#
- Comparing two ValueTuple<T1, T2, T3, T4, T5> in C#
- Comparing two ValueTuple<T1, T2, T3, T4> in C#
- Comparing two ValueTuple<T1, T2, T3> in C#
- Comparing two ValueTuple<T1, T2> in C#
- Comparing two ValueTuple<T1> 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 email@example.com. 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.