Thursday, June 20, 2013

Make readonly data member without using readonly keyword.

In my previous post I have explain what is readonly modifier and how it work with. And we have learned that readonly keyword is need to use to make readonly data member. Now I am going to show you how to implement readonly field without using readonly modifier in c#.

If still now you are finding answer…. then go ahead and look below code.  The trick is very simple just declare set property as a private in your property definition for data member ,then it will not allow anyone to modify anywhere. Now you may thinking then how we will initialize value in private property? Again answer is very simple –Using constructor.

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 string Name
        {
            get;
            private set;
        }

        public string Surname
        {
            get;
            private set;
        }

        public CreateUser(String Name, String Surname)
        {
            this.Name = Name;
            this.Surname = Surname;
        }
    }

    class Program
    {
        static void Main(string[] args)
         {
             CreateUser objUser = new CreateUser("Sourav","Kayal");
             Console.WriteLine(objUser.Name + objUser.Surname);
             Console.ReadKey();
         }
    }
}

And if you try to assign value in this private property then it will not allow to do that.


2 comments:

  1. Hi,nice program for Making readonly data member without using readonly keyword.Thanks..

    ReplyDelete