Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C#
I am calling some string constant value of a library (dll) from my application. So what should use i.e. readonly or constamt for those constant in the library. What is the difference?
 
Please forgive me if this question is too naive.
 
Thanks.
Posted 17-Mar-12 18:10pm
Comments
Clifford Nelson at 18-Mar-12 5:36am
   
I think it is interesting by every answer was downvoted to 2 by someone, and left no reason. Every answer. Also the question was voted 3 twice. Think that is interesting. I voted a 5 for the question because it is not obvious, and think it is good question.
SAKryukov at 19-Mar-12 3:35am
   
I voted 4 for this question and mentioned it's not so naive. However, it's not quite correct. The questions "what's the difference between {0} and {1}" are not logically correct. What's the difference between apple and Apple. Let's say, it was some shorthand form...
 
As to the answers, it's starting to look funny during last week or so. No, not all answers are down-voted; I have some which were not. The pattern is different. It's like at least two people comes (I say "two" because they have different ranks; they give -2 and -4), down-vote a block of some 5 of my answers by 1 or 2 and go. It looks like they don't really look at the content -- it happens very quickly (sometimes I looked at the votes twice after a short time span) and down-vote a block of answers in a row. A couple of secret haters, it looks like. Just funny but annoying...
 
--SA
Clifford Nelson at 19-Mar-12 10:47am
   
Agreed, the question is not quite correct. And true, I was wrong.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

No, this is a good question, not so naive. Constant has one limitation: its value should be "statically known". It means, known during compilation. Such thing as, for example, a result of calculation of some function is not known; its value can be calculated only during run-time.
 
static class NonModifiableDeclarationSet {
    internal const int SomeInteger = 5;
    internal const int SomeOtherInteger = SomeInteger * 10; //constant expression
    // won't compile:
    //internal const double SomeFloatingPointValue = System.Math.Acos(-1d);
    // will work:
    internal static readonly double SomeFloatingPointValue = System.Math.Acos(-1d);
}
 
In this example, SomeFloatingPointValue will be initialized during run time when by the moment it is used, but it cannot be modified after it it initialized, which important for maintenance and as a fool-proof feature. It can also be initialize in a constructor. This effect could not be achieved with const.
 
Please see:
http://msdn.microsoft.com/en-us/library/acdd6hb7%28v=vs.100%29.aspx[^].
 
—SA
  Permalink  
v2
Comments
(__Aaron__) at 17-Mar-12 23:41pm
   
Great answer Thank you very much SA.
SAKryukov at 17-Mar-12 23:47pm
   
You are very welcome.
Good luck, call again.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

One difference is that
 
A constant value will be embedded in the executable file at compile time, and substitutes it at all places wherever it is used. So, if the constant value is changed in the library, which is referenced by your application, then your application also requires to be re-compiled.
 
A read only variable is read by the program at run time. So, if the value of the read only variable is changed in the library, which is referenced by your application, without recompiling your application, the new value of the read only variable will be read by the program.
 
[edit]An example added to elaborate the above points[/edit]
//Project 1. Main application
using System;
 
namespace ConstReadOnlyTest {
    class Program {
        static void Main(string[] args) {
            Console.WriteLine("Value of Constant from Library: {0}", SupportingLib.Class1.ConstString);
            Console.WriteLine("Value of Read ony variable from Library: {0}",SupportingLib.Class1.ReadOnlyString);
            Console.ReadKey();
        }
    }
}
//Project 2. Referenced library, procured from other company say Comapany A.
//The version of compile lib is say 1.0.0.0
using System;
 
namespace SupportingLib {
    public class Class1 {
        public const string ConstString = "Constant";
        public static readonly string ReadOnlyString = "Readonly";
    }
}
 
When I compile this code and run it the output is
Value of Constant from Library: Constant
Value of Read ony variable from Library: Readonly
My application is shipped. Later, a change is made in the referenced library
and Company A supplied me new compiled library with same version 1.0.0.0
 
This is the changed code in the referenced library
 public const string ConstString = "Constant Changed";
 public static readonly string ReadOnlyString = "Readonly Changed";
 
Without recompiling my application I have only supplied the new compiled version of the referenced library to the user. Then the output is
 
Value of Constant from Library: Constant
Value of Read ony variable from Library: Readonly Changed
 
The reason being when I compiled my application the string "Constant" was copied from the referenced assembly and placed in my executable code. Whereas, for Read only variable the program reads from the referenced assembly at run time.
 
So, when I supplied new compiled library the program did read the read only variable from the new compiled referenced library. Hence in the second line of output we got: "Readonly Changed"
Whereas the program used the constant from within my application so the value "Constant" is printed in the first line.
 
Hope I clarified what I thought.
  Permalink  
v4
Comments
Mohammad A Rahman at 17-Mar-12 23:27pm
   
Exactly to the point :)
ProEnggSoft at 18-Mar-12 0:55am
   
Thank you
(__Aaron__) at 17-Mar-12 23:42pm
   
Thank you
SAKryukov at 17-Mar-12 23:46pm
   
"So, if the constant value is changed in the library, which is referenced by your application, then your application also requires to be re-compiled." Not true. It only depends on versining. The dependent application will simply behave differently.
 
"A read only variable is read by the program at run time." What do your mean "read"? It's in the memory, all objects are read in this sense. Essentially, it is initialized during run-time. As to the re-compilation of the application depending on the library, the situation is the same as with constant.
 
Sorry, I have to vote 2.
--SA
ProEnggSoft at 18-Mar-12 0:55am
   
Thank you.
To make my point clear, I have added an example in My Solution
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

'const':
Can't be static.
Value is evaluated at compile time.
Initiailized at declaration only.
 
'readonly':
Can be either instance-level or static.
Value is evaluated at run time.
Can be initialized in declaration or by code in the constructor.

This means that variable that is changed (initialized) only in constructor should be readonly.
 
It is generally considered better to use readonly because if a const is changed then all the clients. However, const is faster.
  Permalink  
Comments
Mohammad A Rahman at 17-Mar-12 23:28pm
   
Good answer.
(__Aaron__) at 17-Mar-12 23:41pm
   
Thank you
SAKryukov at 17-Mar-12 23:42pm
   
Const cannot be static is wrong! Const is always static, and therefor the keyword "static" would be redundant.
Put a const in a static class to make sure.
 
"Better to use readonly" is wrong. False motivation. What do you mean "const is changed"? It is not changed.
 
Sorry, I have to vote 2.
--SA
Clifford Nelson at 18-Mar-12 5:49am
   
I doubt you have ever read "Effective C#: 50 Specific Ways to Improve Your C#" by Bill Wagner, using readonly is recommended. Obviously you are a better authority than Bill Wagner. When I talk about a constant being changed, it is in a large project, and there are issues. Read "Effective C#: 50 Specific Ways to Improve Your C#". Might make you a better programmer. Sorry about the error on static. Not sure why that was stated, but read it somewhere else.

Do a little reseach before your snap decisions.
SAKryukov at 18-Mar-12 12:41pm
   
No, I did not read it. Thank you very much for the advice. I would prefer not loosing my chances to do anything better. I must only need to note, that no book can be authority to me before I decide it by myself; and this does not depend on how much or little I know on the topic. As to C# and .NET in particular, I do remember couple of books with considerable mistakes or with chapters where the author does not understand the essence and tries to conceal it. I've leaned very early to trust only the facts, not authorities. Hope the book you recommended is much better.
 
By the way, you should have some reason to recommend it to me. I mean, if you can offer me direct criticism, I would be grateful for that. In particular, could you please explain where is my mistake and what should I research. I would need to check up and fix it, if this is a mistake.
By the way, if you simply change the text of your answer, I would gladly change my vote.
 
Thank you again,
--SA
Clifford Nelson at 18-Mar-12 23:53pm
   
I can recommend it to you because other people hold the book in high regard. The idea is to learn from other people's successes. Not as good is to learn from other people failures. Worse is to have to learn from your own failures. As Newton stated: "If I have seen further it is by standing on ye sholders of Giants." Newton would not have been able to make the contribution he made without those that came before.
Clifford Nelson at 19-Mar-12 10:48am
   
One other note from above. I have read the book, and I thought it had good ideas. Some of th discussion was above my head, but seemed like Bill Wagner knew what he was saying.
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 5

The below link has very good explanation
 
Difference between const and readonly
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
0 DamithSL 425
1 OriginalGriff 184
2 BillWoodruff 170
3 Zoltán Zörgő 165
4 Maciej Los 163
0 OriginalGriff 7,854
1 DamithSL 5,949
2 Sergey Alexandrovich Kryukov 5,449
3 Maciej Los 5,084
4 Kornfeld Eliyahu Peter 4,539


Advertise | Privacy | Mobile
Web04 | 2.8.141223.1 | Last Updated 19 Jul 2013
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100