i have set mName, mContact and memail as my variables.. and i want to use them in setter and getters.. can any body help me doing so? only want to know the syntax..
regards..
i have set mName, mContact and memail as my variables.. and i want to use them in setter and getters.. can any body help me doing so? only want to know the syntax..
regards..
Hi,
in VS 2005:
class TimePeriod
{
private double seconds;
public double Hours
{
get { return seconds / 3600; }
set { seconds = value * 3600; }
}
}
in VS 2008:
public int CustomerId { get; set; }
//private declaration and property in one line coming with .net 3.5
If you have an existing private variable and you want to expose some public properties then you should do the following:
private string mName;
public string Name
{
get
{
return mName;
}
set
{
mName = value;
}
}
You could also avoid the need for the internal private variable by using a Automatic Properties:
public string Name { get; set; }
As JWL has pointed out in the comments you can also set modifiers on getters and setters. Valid modifiers are private
/internal
/protected
.
public string Name { get; private set; }
public string Name { protected get; set; }
Set your cursor inside of the field (Private int _i;
) and Ctrl R + E This will create the property accessors for you :)
It is also a good practice to implement checking, whether setting up the private variable is really necessary. Like this>
private string mName;
public string Name
{
get
{
return mName;
}
set
{
if ( value != mName )
{
mName = value;
}
}
}