C # const & readonly

Source: Internet
Author: User
Const is a constant, readonly is read-only, and "blog Er" knows that :)
So what are their differences? My personal summary is as follows:
I. Assignment
1) The variable modified by const must be assigned an initial value during definition, and variable values cannot be changed at other locations;
2) variables modified by readonly can be assigned values during definition or in the constructor. Variable values cannot be changed in other positions.
Ii. Call
1) The variable modified by const needs to be called using the class name, just like a static member.
2) The variable modified by readonly must be called by an object.
III,Code
Example:
Public class constreadonly
{
// Public const string firstname; // Error: initialization is required when the const variable is defined.
Public const string lastname = "landpy ";
Public readonly string age = "0 ";
Public constreadonly ()
{
Age = "27 ";
}
Public void deal ()
{
// Age = "123 "; // Error: readonly can be assigned only when the constructor or definition is used.
// Lastname = "Peter "; // Error: the const value can only be assigned at definition.
String TMP = string. empty;
TMP = constreadonly. lastname;
// TMP = constreadonly. Age; // Error: variables modified by readonly can only be called by objects.
Constreadonly = new constreadonly ();
// TMP = constreadonly. lastname; // Error: the variable modified by const can only be called by Class Name
TMP = constreadonly. Age;
}
}

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.