Can anybody help me with the syntax of setters and getters?
i have set mName, mContact and memail as my variables.. an开发者_JAVA技巧d i want to use them in setter and getters.. can any body help me doing so? only want to know the syntax..
regards..
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; }
Visual Studio Tip:
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;
}
}
}
精彩评论