Thursday, June 20, 2013

Readonly modifier in C#

Hi friend! how are you ? I am fine and have set some goal, I will tell those later. Let’s learn readonly modifier in today’s session.

Let me explain SMDN‘s documentation in my own word. Readonly is a modifier in c# which can modify one member of class in readonly mode. And once the value is assign to readonly member it’s not possible to alter or re-initialize again.

How to set value in readonly member :-
In two fashion we can set value to readonly member.

         1) In time of declaration

When we are declaring member that time immediately we can assign value to member
For example
       public readonly Int32 Age = 25;

      2)       Within constructor of class

It’s the second option to initialize readonly member. Just assign value within constructor of class. Like,

public CreateUser()
        {
            CurrentTime = DateTime.Now;
        }



Now you may think. When to use readonly?
Think such situation, When user will register in your website automatically you want to set registration date and time for particular user and you don’t want to alter it any more. Then simply define your register date member as readonly modifier. And any code cannot able to alter your data field value. Let’s see below code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.Data.SqlClient;

namespace BlogProject
{
    class CreateUser
    {
        public readonly DateTime CurrentTime;
        public readonly Int32 Age = 25;
        public string UserName{get;set;}

        public CreateUser()
        {
            CurrentTime = DateTime.Now;
        }
    }

    class Program
    {
        static void Main(string[] args)
         {
             CreateUser obj = new CreateUser();
            
             obj.UserName = "Sourav Kayal";
             Console.WriteLine("Name:- " + obj.UserName);
             Console.WriteLine("Age:- " + obj.Age);
             Console.WriteLine("Registration Time:- " + obj.CurrentTime);
             Console.ReadKey();
         }
    }
}


Noe if you try to try to assign value or modify value in readonly field then it won't allow to do that. Here for your clarification i am trying to assign value in readonly data member and  my compilar it not allowing me.


No comments:

Post a Comment