What do you mean by properties in C#?

 Posted by Abhisek on 1/21/2010 | Category: C# Interview questions | Views: 6745
Answer:

Property acts as a cross link between the field and the method . Actually it behaves as a field. We can retrieve and store data from the field using property.

The compiler automatically translates the field like property into a call like special method called as 'accessor" . In property there are two accessor and that are used to save value and retrieve value from the field. The two properties are 'get' and 'set'.

The get property is used to retrieve a value from the field and the set property is used to assign a value to a field .

Depending on there use properties are categorised into three types,

ReadWrite Property :- When both get and set properties are present it is called as ReadWrite Property.

ReadOnly Property :- When there is only get accessor it is called as ReadOnly Property.

WriteOnly Property :- When there is only set accessor, it is called as WriteOnly Property.


Asked In: Many Interviews | Alert Moderator 

Comments or Responses

Posted by: chpurnima-3216 on: 2/4/2010
Set of functions that can be accessed directly from the client (in a similar way to the public fields of the class)

Properties Example:

//C#: Property
//Author: rajeshvs@msn.com
using System;
class MyClass
{
private int x;
public int X
{
get
{
return x;
}
set
{
x = value;
}
}
}
class MyClient
{
public static void Main()
{
MyClass mc = new MyClass();
mc.X = 10;
int xVal = mc.X;
Console.WriteLine(xVal);//Displays 10
}
}

Remember that a property should have at least one accessor, either set or get. The set accessor has a free variable available in it called value, which gets created automatically by the compiler. We can't declare any variable with the name value inside the set accessor.

Note:
1. To create read-only property, simply omit the set accessor from the properties definition
2. To create write-only, omit the get accessor.
3. C# doesn’t permit setting different access modifiers to get and set. Only public get and protected set.

Ex: public string ForeName
{
get
{
return forename;
}
}
protected void setForeName(string value)
{
if(---) forename = “so so”
else forename = value;
}

Login to post response