Wednesday, 4 June 2014

C# Tutorial-Basics-Constants

Unlike variables, constants retain their values. 
Once initialized, they cannot be modified. Constants are created with the const keyword.

using System;

public class Constants
{
    static void Main()
    {
        const int WIDTH = 100;
        const int HEIGHT= 150;
        int var = 40;

        var = 50;

        // WIDTH = 110;
    }
}

In this example, we declare two constants and one variable.

const int WIDTH = 100;
const int HEIGHT= 150;
We use the const keyword to inform the compiler, that we declare a constant. It is a convention to write constants in upper case letters.

int var = 40;

var = 50;
We declare and initialize a variable. Later, we assign a new value to the variable. It is legal.

// WIDTH = 110;
This is not possible with a constant. If we uncomment this line, we will get a compilation error.

No comments:

Post a Comment