C# Properties 👷🏼♂️👷🏼♀️
- Adds a layer of abstraction between values and external interface. Effectively they are getters and setters with boilerplate code removed
- Rather than returning the value of an internal member, can return a calculated value. Doing the work of a small method (e.g. IsListEmpty() ) while again reducing boilerplate code
- The output of properties can be treated as data (for example in the inclusion of data tables), this is useful when using properties as the output of methods (as in point 2 above)
public class Time
{
public int Hour
{
get
{
return // some value;
}
set
{
// do some work here;
}
}
}
Declaring the variable for the property is not needed in the newer versions of C#. Unless you are attempting to manually save the value in the get block.
The default version of this is...
public class Time
{
public int Hour // capitalized
{
get; private set;
}
}
Example
public int someVar { get; set; }
public bool hasList
{
get
{
return myList != null and myList.Count>0;
}
}