If tomorrow never comes

The meaning of life is creation,which is independent an boundless.

导航

const和readonly(一)

Posted on 2009-04-17 21:03  Brucegao  阅读(333)  评论(0编辑  收藏  举报

The const keyword is used to modify a declaration of a field or local variable. It specifies that the value of the field or the local variable is constant, which means it cannot be modified. For example:

const int x = 0;
public const double gravitationalConstant = 6.673e-11;
private const string productName = "Visual C#";

 

Remarks:

The type of a constant declaration specifies the type of the members introduced by the declaration. A constant expression must yield a value of the target type, or of a type that can be implicitly converted to the target type.

A constant expression is an expression that can be fully evaluated at compile time. Therefore, the only possible values for constants of reference types are string and null.

The constant declaration can declare multiple constants, such as:
 

public const double x = 1.0, y = 2.0, z = 3.0;

The static modifier is not allowed in a constant declaration.

A constant can participate in a constant expression, as follows:

public const int c1 = 5;
public const int c2 = c1 + 100;


Notes: 

The readonly keyword differs from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, although a const field is a compile-time constant, the readonly field can be used for run-time constants, as in this line: public static readonly uint l1 = (uint)DateTime.Now.Ticks;

Example:

// const_keyword.cs
using System;
public class ConstTest 
{
    
class SampleClass 
    {
        
public int x;
        
public int y;
        
public const int c1 = 5;
        
public const int c2 = c1 + 5;

        
public SampleClass(int p1, int p2) 
        {
            x 
= p1; 
            y 
= p2;
        }
    }

    
static void Main() 
    {
        SampleClass mC 
= new SampleClass(1122);   
        Console.WriteLine(
"x = {0}, y = {1}", mC.x, mC.y);
        Console.WriteLine(
"c1 = {0}, c2 = {1}"
                          SampleClass.c1, SampleClass.c2 );
    }
}

 

My local constant = 707

 

continue……