const and readonly keywords in C#

const variables are implicitly static and they need to be defined when declared.

readonly variables are not implicitly static and can only be initialized once.

E.g.: You are writing a car racing program in which the racing track has a fixed length of 100 Km. You can define aconst variable to denote this as:

private const int trackLength = 100;

Now, you want the user to enter the number of cars to race with. Since this number would vary from user to user, but would be constant throughout a game, you need to make it readonly. You cannot make it a const as you need to initialize it at runtime. The code would be like:

public class CarRace
    //this is compile time constant
    private const int _trackLength = 100;
    //this value would be determined at runtime, but will
    //not change after that till the class's 
    //instance is removed from memory
    private readonly int _noOfCars;

    public CarRace(int noOfCars)

    public CarRace(int noOfCars)
        ///Get the number of cars from the value 
        ///use has entered passed in this constructor
        _noOfCars = noOfCars;

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s