C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Communities   Interview   Jobs   Projects   Offshore Development    
Silverlight Tutorials | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Revenue Sharing |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...

New Feature: Community Sites: Create your own .NET community website and start earning from Google AdSense ! It's Free !




Differences between constant and read only variable


Posted Date: 08 Feb 2008    Resource Type: Code Snippets    Category: C# Syntax

Posted By: Litty Thomas       Member Level: Silver
Rating:     Points: 7



Initialization of a Const member values are done at the declaration of the member whereas Readonly can be initialized at the declaration as well as in a constructor. i.e; Const members is a compile-time constant whereas readonly fields can be used as runtime constant (value assigned only at runtime).

Constant values cannot be changed after its initialization. But read only variables values can be changed inside the constructors.

Constant variables can be assigned to the readonly. But readonly variables can’t be assigned to the constant variables.




using System ;
class ConstantSample
{
public static void Main ()
{
contantvalue objcontantvalue=new contantvalue(10);

int S=objcontantvalue.k;
Console.WriteLine(S);
}
}
class contantvalue
{
public const int i=10 ; //constant initialization
public readonly int k=i; //readOnly initialization
public contantvalue(int Kchange )
{
k=k+Kchange; //readOnly initialization in constructor
}
}






Responses

Author: Gaurav Arora    15 Aug 2008Member Level: Gold   Points : 2
Hi Thomas,

Its a good snippet. I want to mark my entry here too, please check this article:http://www.dotnetspider.com/resources/20259-Variables-Constants-ReadOnly.aspx.

This provides more detail for subject.

Enjoy programming!

Thanks & regards,
Gaurav Arora


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Difference between const and readonly  .  Const and readonly difference  .  

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: Event Handling in C#: Custom event Handlers in .NET
Previous Resource: Using a Generics List Collection in C# to retrieve all folders, subfolder, and fold
Return to Discussion Resource Index
Post New Resource
Category: C# Syntax


Post resources and earn money!
 
Related Resources



dotNet Slackers   BizTalk Adaptors    Web Design

masks masks masks

Contact Us    Privacy Policy    Terms Of Use