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 pair of methods) that act look and like a field when you want to get or set a value, thereby simplifying the syntax.
Defining read-only properties
In the Person2.cs
file, inside the Person
class, add the following code to define three properties:
- The first property will perform the same role as the
GetOrigin
method using theproperty
syntax that works with all versions of C# (although, it uses the C# 6 and later string interpolation syntax). - The second property will return a greeting message ...
Get C# 7 and .NET Core: Modern Cross-Platform Development - Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.