Controlling access with properties and indexers
Earlier, you created a method named GetOrigin
that returned a string
containing the name and origin of the person. Languages such as Java do this a lot. C# has a better way: properties.
A property is simply a method (or a pair of methods) that acts and looks like a field when you want to get or set a value, thereby simplifying the syntax.
Defining read-only properties
A readonly
property only has a get
implementation.
- In
PersonAutoGen.cs
, in thePerson
class, add statements to define three properties:- The first property will perform the same role as the
GetOrigin
method using the property syntax that works with all versions of C# (although, it uses the string interpolation syntax from C# 6 and later). - The second property will return a greeting message using the lambda expression body
=>
syntax from C# 6 and later. - The third property will calculate the person's age. ...
- The first property will perform the same role as the