December 2018
Beginner to intermediate
668 pages
15h 30m
English
If the value of a field will never ever change, you can use the const keyword and assign the value at compile time.
Inside the Person class, add the following code:
// constants public const string Species = "Homo Sapien";
Inside the Main method, change the code to look like this. Note that, to read a constant field, you must write the name of the class, not the name of an instance of the class:
WriteLine($"{p1.Name} is a {Person.Species}");
Run the application and view the additional output:
Bob Smith is a Homo Sapien
Examples of the const fields in Microsoft types include System.Int32.MaxValue and System.Math.PI because neither value will ever change, as you can see in the following screenshot:
Read now
Unlock full access