By 19/12/2013 12 Comments

Use const and readonly keyword in C#

What is const and readonly keywords ?

  • Both const and readonly keywords are used to define data that does not change or modify
  • These are also called modifiers
  • They are different from each other

Const keyword

  • It is used to declare the constant fields
  • The constant fields are not variables so they can not be modified or changed
  • Constants can be any valid data types such as boolean, null or strings
  • They can be declared only once, and later can not be changed
  • Const fields must be defined at declaration Because of this and the fact that they cannot change value, it implies that they belong to the type as static fields

readonly keyword

  • readonly fields can be set at declaration or in the constructor
  • readonly field can not be re-initialize in any method within the same class

Following example described the constant and readonly keyword in c#

public class Keywords
{
private const string varCont = "cSharp"; // initialize a field / variable with const keyword
private readonly int verRead; // declare a field / variable with readonly keyword
public Keywords() // define a constructor
{
verRead= 45;//Ok // now, initialize that readonly field / variable in a class constructor
}
public void SomeFunction() // method declaration of type void
{
verRead= 13;//Error! // notice !, try to re-initialize the readonly field again in method
}
}






Posted in: C#.NET

Leave your valuable Comment

Have a natural attraction for women cosmetics and replica watches uk clothes, no
more than two for men the most attractive one, is to make their own driving experience, happy and can serve as the facade of the car, another is to highlight the taste edify sentiment rolex replica watch. The replica rolex is undoubtedly the most fashionable accessories, wear a suit to attend the activities, but also get a decent match on the replica watches .