Understand “readonly” modifier in C#

Sourav.Kayal
Posted by in C# category on for Beginner level | Points: 250 | Views : 3419 red flag

How to use "readonly" modifier in C#

Understand “readonly” modifier in C#

In this article we will learn the importance and uses of “readonly” keyword in C#.  The modifier “readonly” prevents fields from being modify. We can initialize value in “readonly” variable one time and compiler will throw error in time of any modification.

When to use “readonly”?

Sometimes the situation comes where user should not modify default data. For example in time of fill up registration from , the registration data can be specified as “readonly” means user cannot modify the value. There might be facility in application to calculate age from data of birth. According to given date of birth, age will be calculated. In this situation the age field can able to specify as “readonly” variable.

So, those are the scenario where we can use “readonly” modifier to a variable.

Where to specify?

  • We can specify “readonly” to data member of class.
  • Function member cannot possible to modify as “readonly”
  • Properties cannot able to modify as “readonly”.(But there is a trick to create “readonly” property

How to initialize “readonly” field?

We can set value to “readonly” variable either define time or within constructor. Initialization from other place will throw error.

 In below example we will try to initialize “readonly” variable from Main() function. Try to understand below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp
{
    class PersonInfo
    {
        public readonly string name;
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            PersonInfo p = new PersonInfo();
//Wrong initialization
            p.name = "Sourav";
            Console.ReadLine();
        }
    }
}

It will show below error.


Here is another example to initialize “readonly” variable. Have a look on below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp
{
    class PersonInfo
    {
        public readonly DateTime Today = DateTime.Now;
        public readonly string name;
        public PersonInfo()
        {
            name = "Sourav Kayal";
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            PersonInfo p = new PersonInfo();
 
            Console.WriteLine("Date is:- " +p.Today);
            Console.WriteLine("Name is :- " + p.name);
            Console.ReadLine();
        }
    }
}

Here is sample output.


 “readonly” property without “readonly” keyword

In above discussion we have written that, it is possible to create “readonly”  property without “readonly” keyword. In below example we will try to implement “readonly” property. Try to understand below code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApp
{
    class PersonInfo
    {
        public string name { get; private set; }
        public PersonInfo()
        {
            name = "sourav kayal";
        }
    }
 
    class Program
    {
        static void Main(string[] args)
        {
            PersonInfo p = new PersonInfo();
            Console.WriteLine("Name is :- " + p.name);
           
            Console.ReadLine();
        }
    }
}

In this code we have defined set property of name field as private, so that there is no chance of external modification and within constructor of the class we are assigning the value. Here is sample output.


Conclusion:-

In this article we have learned to use “readonly” modifier in C#. The key point of “readonly” modifier is to prevent data from being change. Hope you have understood the concept.

Page copy protected against web site content infringement by Copyscape

About the Author

Sourav.Kayal
Full Name: Sourav Kayal
Member Level: Silver
Member Status: Member,MVP
Member Since: 6/20/2013 2:09:01 AM
Country: India
Read my blog here http://ctrlcvprogrammer.blogspot.in/
http://www.dotnetfunda.com
I am .NET developer working for HelixDNA Technologies,Bangalore in healthcare domain. Like to learn new technology and programming language. Currently working in ASP.NET ,C# and other microsoft technologies.

Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)