What's the differences between readonly & Const in C # difference between readonly and const in C #

Source: Internet
Author: User
1. The similar feature Similarity
GRAMMAR:
Public const int x = 100;
Public readonly int X;
Const variable and readonly variable can not be modified once they are initialized in run-time. However, the main differences between them is the time to be initialized!
The value of the const and readonly variables cannot be changed once initialized. However, the difference between them is that they are initialized at different times.

2 the differences
const variable must be initialized when it's be declared, because its value is set in compile-time before the respective object is constructed. however, readonly can be initialized dynamically. that is to say, its value can be set via class constructor or vairable initiazer (no other feasible ways ).
the const constant must be declared Initialization, because its value is set before the corresponding object structure is compiled. However, readonly can be set dynamically. It can be set either during initialization or in the constructor (other methods are not supported ).
E. G
Public Class A
{< br> Public const m_x = 100;

// Public const m_x = datatime. Now. tricks;
// error! Datatime. now. tricks can not give a exact value for const variable in compile-time.
Public readonly long m_y = datatime. now. tricks;
// It can be initialized via viriable initiazer

Public readonly int m_z;
Public A ()
{< br> m_z = datatime. now. tricks;
// It also can be initialized via constructor;
}< BR >}< br>

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.