properties without body [duplicate]
-
08-07-2021 - |
Question
Possible Duplicate:
What’s the difference between encapsulating a private member as a property and defining a property without a private member?
In C#, usually when I define a property I declare and implement a single line or more for get and set. e.g.
public bool IsThere
{
get { return _isThere; }
set { _isThere = value;}
}
now what does this mean?
public bool IsThere
{
get;
set;
}
Solution
Those are auto-properties. They work the same way as your first example, but allow you to omit the unnecessary source code.
They're best used when there is no longer to your getter/setter methods.
They also allow you to add logic to your getter/setter methods later without breaking any calling code (even though you'll also have to implement the private backing property yourself).
OTHER TIPS
It's an Auto-Implemented Property (automatic property).
The C# compiler will automatically create a private field member for the get/set methods to read/write from.
Note that there are limitations to automatic properties (for now). For example, you cannot use modifiers such as readonly
, though you can still mark it as private set
it isn't quite the same.