You implement a read-only property in a class by implementing the get accessor, but not the set accessor. This will allow client code to read the property’s value, but not write to it directly.
Below is an example of a read-only property for the Dog class. The WhenLastBarked property returns a DateTimevalue indicating the last time that the Dog barked–i.e. the last time that someone called the Bark method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | // Backing variable storing date/time last barkedprivate DateTime lastBarked;// Public property, allows reading lastBarkedpublic DateTime WhenLastBarked{ get { return lastBarked; }}// Bark method also sets lastBarkedpublic void Bark(){ Console.WriteLine("{0}: Woof!", Name); lastBarked = DateTime.Now;} |
We now have a property in the Dog class that we can read from, but not write to.
1 2 | kirby.Bark();DateTime whenHeBarked = kirby.WhenLastBarked; |

