Use of the const and readonly modifiers in C # _c# tutorial

Source: Internet
Author: User

1. Only C # built-in types (Int,double,long, etc.) can be declared as const, and results, classes, and arrays cannot be declared as Const.

2. ReadOnly is a modifier used on a field that is accessed directly by the class name. field.

3. The const must be initialized in the declaration. Can not be modified after that.

4. ReadOnly can be initialized in a declaration or initialized in a constructor, and other circumstances cannot be modified.

 namespace Const_and_readonly {class Program {static void Main (string[] args) {Conso Le. WriteLine ("Half a year have {0} moths", CALENDAR.MOTHS/2);
Direct class name. field Access Const field Calendar test1 = new Calendar (); Console.WriteLine ("Every year has {0} weeks and {1} days", Test1._weeks, test1._days);//readonly field accesses the Calendar by instance test2 =
New Calendar (31, 4);
Console.WriteLine ("January has {0} weeks and {1} days", Test2._weeks, Test2. _days);
Console.readkey ();  Class Calendar {public const int moths =//const must initialize the public readonly int _days=365 in the Declaration;//readonly initialize public in the Declaration
readonly int _weeks; Public calendar ()//readonly initializes {_weeks = ' public calendar ' (int days,int weeks) within the constructor//readonly Initialize {_days = d in the constructor
Ays
_weeks = weeks; public void SetValue (int days,int weeks) {//_days = days; Cannot assign value to read-only field//_weeks = weeks; Cannot assign values to read-only fields}} 

The above is a small set to introduce the C # in the const and readonly modifier usage detailed, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.