Csharp/CSharp Tutorial/Class/const

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Define constants with const keywords

  1. The const modifier is used to declare fields or local variables that cannot be changed.
  2. These variables must be given initial values when they are declared.
  3. const implies static.


using System;
class Constants
{
    public const int value1 = 33;
    public const string value2 = "Hello";
}
class MainClass
{
    public static void Main()
    {
        Console.WriteLine("{0} {1}", 
        Constants.value1, 
        Constants.value2);
    }
}
33 Hello

Local Constants

using System;
class MainClass
{
   static void Main()
   {
      const double PI = 3.1416;
      double area = 2 * 2 * PI;
      
      Console.WriteLine("Radius: {0}, Area: {1}", 2, area);
   }
}
Radius: 2, Area: 12.5664

The use of "const int"

class MainClass
{
  public static void Main()
  {
    const int Length = 3;
    System.Console.WriteLine(Length);
  }
}
3

Use expressions to calculate and display the circumference of a circle

class MainClass
{
  public static void Main()
  {
    const double Pi = 3.14159;
    double diameter = 2.5;
    double circumference = Pi * diameter;
    System.Console.WriteLine("Circumference = " + circumference);
  }
}
Circumference = 7.853975