By 22/07/2015 16 Comments

C# Constants

  • Constants are not variables but these are similar to variables.
  • These variable’s values cannot be changed throughout its lifetime.
  • We prefix a variable with the [const] keyword to make it a constant variable.
  • We cannot assign any value of a variable (non-constant) to a constant.

Example:

using System;
namespace csharpBasic
{
    // start class definition / declaration.
    class Program
    {
        // static main method void type declaration.
        static void Main(string[] args)
        {  
         // String type constant variable declaration and initialization.
            const string programingLanguage = "c#";

         // Re-initialization of already declared constant.
            programingLanguage = "Asp.net"; // Compile-time error!

            // Print constant.
            Console.WriteLine(programingLanguage);
            Console.ReadKey();
        } // End of main method definition.
    }  // End of class.
}

Remember:

  • Constants cannot be prefixed with static modifier because these are static by default.
  • They must be initialized at its declaration time.
  • Once we have assigned a value to them, than that value cannot be overwritten or changed.
  • Constants initialized at compile time.

Advantages of using constants:

  • Constants makes program easier to read.
  • It helps us to prevent mistakes in our program. If we assign another value to already¬†declared and initialized constant than the compiler generates an ERROR.





Next Tutorial →


← Previous Tutorial


Posted in: C# Basics, 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 .