Reprint: readonly and const comparison

Source: Internet
Author: User

Original address: Http://www.cnblogs.com/panjun-Donet/archive/2008/03/28/1127680.html the day before yesterday made a low-level error, is about ReadOnly, summed up a bit:
C # 's readonly keyword can only be used on fields
Public readonly TcpClient Client;
Cannot use readonly!! on class, method, property above
By the way, I looked at the difference between ReadOnly and const:
  • ReadOnly and const are used to identify constants.
  • Const can be used to modify class field or a local variable (local variable), while ReadOnly is used only to modify class field.
  • Const The value of a constant must be clear and constant at compile time, while the readonly constant is a bit different, that is, its value can be compiled at run time, and of course it has to obey the constraint as a constant, that is, the value must be constant.
  • Const constants must be assigned at the same time as they are declared, and ensure that the value is deterministic and constant at compile time, whereas the ReadOnly constant can optionally be given a compile-time determined and constant value at the same time as the declaration, or the initialization of its value is given to the instance constructor (instant constructor) complete. For example: Publicreadonly string m_now = DateTime.Now.ToString (), M_now will change as the runtime situation changes.
  • Const constants are at the class level rather than at the instance object level (Instant object levels), and it cannot be used in conjunction with static . The value of the constant is shared by all instance objects of the entire class (see the remark area later in detail).
  • ReadOnly A constant can be either a class level or an instance object level, depending on its declaration and how the initialization work is implemented. readonly can be used in conjunction with static to specify that the constant belongs to the class level, and the initialization work is done by the static constructor (static constructor) (about how to put the readonly constants are declared as class-level or instance-object-level discourses, see the remark area later .
  • can be const A type that is declared as a constant must be of the following primitive type (primitive type): sbyte ,  byte ,  short ,  ushort ,  int ,  uint ,  long ,  ulong ,  char ,  float ,  double ,  float , bool ,  decimal ,  string .
  • Object , arrays and structs (structs) cannot be declared as Const constants.
  • In general, a reference type cannot be declared as a const constant, with one exception:string. The value of the const constant of the reference type can have two cases,string or null. In fact,string is a reference type, but. NET deals with it especially, which is called string constancy (immutable), which makes the value of string read-only. For information about string constancy, refer to Microsoft. NET Framework Programming (revised edition).

Examples:

using system;

Public class order
{
     public order ()
    {
         guid guid = guid.newguid ();
        id = guid. ToString ("D");
    }

    //  for each order, its order sequence number is a constant that is determined in real time.
    public readonly string ID;

    public override string tostring ()
    < Span id= "Codehighlighter1_242_282_open_text" >{
        return  " order id:  " + ID;
    }
}

Explaintion:

  • If used in conjunction with a database, ID field is usually associated with a table's main key (primary keys), such as the OrderID of the Orders table.
  • The primary health of a database is typically in the following three ways:
    • Automatic increment. You can activate the auto-increment feature by setting the Datacolumn.autoincrement to a true value.
    • Unique name. This is to generate a unique sequence number using the algorithm that you define.
    • GUID (globally unique identifier). You can generate GUIDs from the SYSTEM.GUID structure, as in the previous example.
usingSystem;

ClassCustomer
{
Public Customer (string name, intkind)
{
M_name =$name;kind;
}

public const INT NORMAL = 0;
public const int VIP = 1;
public const int SUPER_VIP = 2;

private StringM_name;
public stringName
{
Get {return m_name;}
    }

private ReadOnly intM_kind;
Public int Kind
{
Get {return m_kind;}
    }

Public override StringToString ()
{
if (M_kind = =SUPER_VIP)
Return "Name:" + m_name + "[SUPERVIP]";
else if (M_kind = =VIP)
Return "Name:" + m_name + "[Vip]";
else
            return "Name:" + m_name + "[Normal]";
}
}


Remarks:

    • In general, if you need to declare constants that are universally recognized and used as a single use, such as PI, golden split ratio, etc. You can consider using const constants, such as: publicconst double PI = 3.1415926;. If you need to declare a constant, but this constant will depend on the actual operation, then thereadonly constant will be a good choice, such as the order number order.id for the first example above.
    • In addition, if you want to represent the default values inside an object, and such values are usually of a constant nature, you can also consider a const. More often than not, when we refactor the source code (using replace magic number with symbolic Constant), the effect of removing magic numbers will be aided by this characteristic of the const .
    • Let's take a look at the following code for whether the variables modified by readonly and const are at the class level or at the instance object level:

Using directives

Namespace Constantlab
{
Class Program
{
static void Main (string[] args)
{
Constant C = new Constant (3);
Console.WriteLine ("Constint =" + Constant.ConstInt.ToString ());
Console.WriteLine ("Readonlyint =" + c.readonlyint.tostring ());
Console.WriteLine ("Instantreadonlyint =" + c.instantreadonlyint.tostring ());
Console.WriteLine ("Staticreadonlyint =" + Constant.StaticReadonlyInt.ToString ());

Console.WriteLine ("Press any key to continue");
Console.ReadLine ();
}
}

Class Constant
{
Public Constant (int instantreadonlyint)
{
Instantreadonlyint = Instantreadonlyint;
}

public const int constint = 0;

public readonly int readonlyint = 1;

public ReadOnly int Instantreadonlyint;

public static readonly int staticreadonlyint = 4;
}
}

    • When using Visual C # to insert the relevant field of constant in main (), it is found that readonlyint and instantreadonlyint need to specify constant instance object intellisence , while Constint and Staticreadonlyint specify the constant class (see the code above). It can be seen that constants modified with const or static readonly are class-level, and readonly -Modified, either directly by assignment or initialized in an instance constructor, Belong to the instance object level.
    • In general, if you need to express a set of related compile-time deterministic constants, you might consider using an enum type (enum) instead of embedding multiple const constants directly into the class as field, but neither of these approaches is absolutely superior or inferior.

usingSystem;

EnumCustomerkind
{
SUPERVIP,
Vip
Normal
}

classCustomer
{
Public Customer (Stringname, Customerkind kind)
{
M_name =name;
M_kind =Kind
}

private StringM_name;
public stringName
{
Get {return m_name;}
    }

PrivateCustomerkind M_kind;
PublicCustomerkind Kind
{
         get { return  m_kind; }
&NBSP;&NBSP;&NBSP;&NBSP;}

     public override string ;
    }
}

    • However, when this combination of code that uses enumerations and conditionals prevents you from making more flexible extensions and may cause future maintenance costs to increase, you can use the Replace Conditional with polymorphism to refactor the code instead. (For a detailed description of polymorphism, see "Are You polymorphic today?") "article. )

Comments:

    • readonly field should be translated into "read-only Domain", here is to unify the translation of the language to the amount of both it and the const are said to be "constant", I hope not to cause misunderstanding.

Reprint: readonly and const comparison

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.