Click here to Skip to main content
15,891,670 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
Hi Friends,
What is difference between use of const and static

EQ.
public static string CSS_SELECTOR_TEMPLATE = "{0} > a";


I can even write the same as
public const string CSS_SELECTOR_TEMPLATE = "{0} > a";


Only difference I found is
static variable can be replaced with new value, but const cannot.

Both can be accessed without creation of object of the class, like

GridCellCssSelectorEvaluator.CSS_SELECTOR_TEMPLATE


Can anyone tell me more usefulness of both?

Thanks in advance
Posted
Comments
PrakashCs.net 4-Jul-14 1:02am    
static variable value can be change if it is static readonly variable in the constructor .
Sergey Alexandrovich Kryukov 4-Jul-14 1:10am    
"Only"?!!! Don't you think this is dramatic difference?
—SA

1 solution

refer answers 3 in this link[^]
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 4-Jul-14 1:13am    
Which one do you call "answer 3"? Two of those answers would earn my vote of 2. They are really bad.
—SA
PrakashCs.net 4-Jul-14 1:23am    
answer 3 in link i.e.
When you use a const string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.

A static readonly string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.

This also means that a static readonly string can use non-constant members, such as Environment.UserName or DateTime.Now.ToString(). A const string can only be initialized using other constants or literals.
Also, a static readonly string can be set in a static constructor; a const string can only be initialized inline.

Note that a static string can be modified; you should use static readonly instead.
Sergey Alexandrovich Kryukov 4-Jul-14 1:36am    
Thank you. I'll up-vote your answer. But not by 5, for being so unclear. This answer is not 3, is marked as 41. I thought it was 3rd answer from top, which is bad.
—SA
Maciej Los 4-Jul-14 1:53am    
It is not 3 and not 41;
3 means there are 3 answers, 41 is the count of upvotes ;)
Sergey Alexandrovich Kryukov 4-Jul-14 2:06am    
Damn, they don't show answer IDs, probably to let people make mess.
Finally, we have one who can read; thank you, Maciej.
How are you?
—SA

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900