Breaking News

Editors Picks

Tuesday, June 21, 2011

readonly keyword in c sharp


readonly


The readonly keyword is a modifier that you can use on fields. When a field declaration includes a readonly modifier, assignments to the fields introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.
http://i.msdn.microsoft.com/Hash/030c41d9079671d09a62d8e2c1db6973.gifExample


In this example, the value of the field year cannot be changed in the method ChangeYear, even though it is assigned a value in the class constructor

class Age
{
    readonly int _year;
    Age(int year)
    {
        _year = year;
    }
    void ChangeYear()
    {
        //_year = 1984; // Compile error if uncommented.
    }
}
You can assign a value to a readonly field only in
the following contexts: 

·  When the variable is initialized in the declaration, for example:
·         public readonly int s = 52;
·        For an instance field, in the instance
constructors of the class that contains the field declaration.
he readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants
:

No comments :

Post a Comment

Contact Us

Name

Email *

Message *