C #. NET Quiz:const vs. readonly

Source: Internet
Author: User
Tags constant
Ado

About the const and ReadOnly in C # presumably using C #. NET development friends are very familiar with it? Summing up the const and readonly are just a few:

Once the const and readonly values are initialized, they can no longer be overwritten;
A const can be initialized only at declaration time, and ReadOnly may be initialized at the time of declaration or in the constructor;
Const implicitly static, can not write static const;readonly is not the default static, if necessary can write static readonly;
A const is a constant that is statically parsed at compile time (so its expression must be evaluated when compiled); ReadOnly is a constant that dynamically resolves during the runtime;
A const can be used to decorate a member of a class, or to modify a local variable in the body of a function; readonly only for members in a decorated class
A const can only decorate an builtin type (except for a string), and readonly may modify the reference type. New
There is nothing to say in the first few, but there are some articles to be done on the 4th article. Try the example below to see if it's the same as you think.

Show All

0. Constants and static read-only variable class library (filename Consts.cs)

public class Consts
{
? Public const String const = "Const";
? public static readonly String readonly = "ReadOnly";
}

Executes csc/t:library Consts.cs compile output Consts.dll.

1. Client (filename Quiz.cs, compilation option/r:consts.dll)

public class Quiz
{
? public static void Main ()
? {
??? System.Console.WriteLine (Consts.const);
???? System.Console.WriteLine (consts.readonly);
? }
}

Perform the CSC Quiz.cs compile output Quiz.exe.

2. Perform Quiz.exe and output as follows:

Const
ReadOnly

3. Now replace the values of the two constants in Consts.cs with uppercase and recompile Consts.cs (Quiz.exe unchanged, still refer to Consts.dll). Then execute the Quiz.exe, the output will be ... What is it? (const READONLY)



Related Article

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.