Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to use Constant & Readonly

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 200
    Comment on it

    Constant and ReadOnly is the C# keyword and use to hold a value for a life of a Program. As the Name implies we can not change the value of Constant and ReadOnly type variable. But there is some difference between them.

    Constant : Constants are declared using a "const" keyword. Constant should be assigned the value at the time of declaration, so value known at compile time. Now whenever we declare a variable as const, the C# compiler set it's value directly into Intermediate Language (MSIL). EX : we are using Age=12 Variable as Const, and this variable using in 10 times in my program. so at the time of compilation, CLR compiler set the Age Value = 18 for all it's reference in our program. Hence this will increase our program performance.

    In a live scenario, If i am making an indian domain matrimonial project, where i know that the minimum age of a bride should be 18 years and for groom 21 year, and that will never change in my program. So here i fix this value as a Const at compile time and wherever i am using this variable in my program, C# compiler set it's value for all place (reference) at compile time.

    class Program
    {
        const int _brideAge = 18;
        const int _groomAge = 21;
    
        static void Main()
        {
        _brideAge = 20 ; // This causes a compile-time error:
        Console.WriteLine(_brideAge );         // Access constant
        }
    }
    

    ReadOnly : We can assign readonly var at the time of compile time or run time. If we not assign value at the time of declaration then we must assign the value with in constructor for the same class.

    In a live scenario, If i am making an Account domain project, where rate of Income tax may change every year, but remain same for same year. So here we maintain the tax value in our Database and on run time we set the value in our integer type variable ex Income tax = 12%. But any one can change my **incometax** variable value, So to prevent it i will declare my variable as readonly. So now my variable value determine at run time and this value can't be change in program.

    class Test
    {
        readonly float _incomeTax;  // readonly int
    
        public Test()
        {
        _incomeTax = 12.4   // Can perform DB operation here to set value at run time
        }
    
    }
    

    Reference : http://www.dotnetperls.com/readonly

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: