What is the difference between readonly and constant in c#

Answer Posted / anver sadat

A const must be initialized at the time of its creation. A
readonly field can be assigned to once in the class
constructor allowing you to pass in the value at run-time.
Declaring fields as const protects both you and other
programmers from accidentally changing the value of the
field. Also note that with const fields, the compiler
performs some optimization by not declaring any stack space
for the field. The readonly keyword is similar to const,
with two exceptions. First, the storage of a readonly field
is the same as a regular read-write field, and thus there is
no performance benefit. Secondly, readonly fields can be
initialized in the constructor of the containing class.

Use of the 'static' keyword, however, associates a field
with a class itself, so there will only ever be one such
field per class, regardless of the number of the class
instances (and the static field will exist even if there are
no class instances). A static field need not be constant,
however; it can be changed by code.

Is This Answer Correct ?    5 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is .edmx file?

518


What is sqladapter c#?

520


What is a class in unity?

476


What is the difference between parse and tryparse in c#?

484


Why ienumerable is used in c#?

465






What is the different types of private assembly and shared assembly?

490


What is difference between hashtable and dictionary in c#?

485


what is the difference between convert.tostring() and tostring() functions ?

559


What is strong data type in c#?

474


If you define a user defined data type by using the struct keyword, is it a value type or reference type?

508


Is unboxing an implicit conversion?

526


How do I do implement a trace?

529


What do you mean by expression tree?

436


In how many ways you can overload a method?

580


Which language is used for desktop application?

475