Properties
In this chapter you will learn:
What is properties
Properties are fields with logics.
C# uses get
and set
keywords to declare a property.
A property consists of a name along with get
and set
accessors.
The accessors are used to get and set the value
of a variable.
The general form of a property is shown here:
type propertyName {/*from j a v a 2 s . co m*/
get {
// get accessor code
}
set {
// set accessor code
}
}
A property cannot be passed as a ref
or out
parameter to a method.
You cannot overload a property.
A property should not alter the state of the underlying
variable when the get
accessor is called.
get
and set
are called property accessors.
get
accessor is called when reading the property
and set
accessor is called when assigning value to the property.
value
is the parameter, which designates the value being assgined.
A property can have the following modifier:
- static
- public
- internal
- private
- protected
- new
- virtual
- abstract
- override
- sealed
- unsafe
- extern
using System;/* j a v a 2s . c o m*/
class Rectangle{
private int width;
public int Width{
get{
return width;
}
set{
width = value;
}
}
}
class Program
{
static void Main(string[] args)
{
Rectangle r = new Rectangle();
r.Width = 5;
Console.WriteLine(r.Width);
}
}
The output:
Next chapter...
What you will learn in the next chapter:
- Add statement to the getter and setter of a property
- Put logic to property setter
- throw Exception from property setting