C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Read and Write - Only ( Properties ) in C#


Posted Date: 01 Oct 2009    Resource Type: Articles    Category: .NET Framework
Author: Muhammad JavedMember Level: Gold    
Rating: 1 out of 5Points: 10



Read and Write - Only ( Properties ) in C#


This is highly observed in common scenariowhen a property definition contains the get and set accessors, that property can be read as well as
written. To make a property read - only, you simply leave out the set accessor, like this:

public int ID
{
get
{
return _ID;
}
}

You can now read but not write values into the ID property:

Console.WriteLine(c1.ID); //---OK---
c1.ID = 1234; //---Error---
Likewise, to make a property write - only, simply leave out the get accessor:
public int ID
{
set
{
_ID = value;
}
}
//You can now write but not read from the ID property:
Console.WriteLine(c1.ID); //---Error---
c1.ID = 1234; //---OK---

You can also restrict the visibility of the get and set accessors. For example, the set accessor of a public
property could be set to private to allow only members of the class to call the set accessor, but any
class could call the get accessor. The following example demonstrates this:

public int ID
{
get
{
return _ID;
}
private set
{
_ID = value;
}
}

In this code, the set accessor of the ID property is prefixed with the private keyword to restrict its
visibility. That means that you now cannot assign a value to the ID property but you can access it:
c.ID = 1234; //---error---
Console.WriteLine(c.ID); //---OK---
You can, however, access the ID property anywhere within the Contact class itself, such as in the Email
property:

public string Email
{
get
{
//...
this.ID = 1234;
//...
}
//...
}



Responses


No responses found. Be the first to respond and make money from revenue sharing program.

Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
Write only properties in C#  .  Read only properties in c#  .  Read and Write Only Properties in C#  .  

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: Properties in C Sharp
Previous Resource: Keyword "this" in C#
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use