In this chapter, we discussed additional class concepts. The time examples concluded with a complete class declaration consisting of private
data, overloaded public
constructors for initialization flexibility, properties for manipulating the class’s data and methods that returned string
representations of a time in two different formats.
We mentioned that the this
reference is used implicitly in a class’s non-static
methods and properties to access the current object’s instance variables and other non-static
members. You saw explicit uses of the this
reference to access the class’s members (including shadowed instance variables) and how to use keyword this
in a constructor to call another constructor of the same class.
You saw that composition enables a class to have references to objects of other classes as members. We discussed C#’s garbage-collection capability and how it reclaims the memory of objects that are no longer used. We motivated the notion of static
class variables and demonstrated how to declare and use static
variables and methods in your own classes. You saw how to declare and initialize readonly
variables and we discussed that the compiler automatically marks as readonly
the instance variable for a getter-only auto-implemented variable.
We also showed how to use Visual Studio’s Class View and Object Browser windows to navigate the classes of the Framework Class Library and your own apps to discover information about those classes. You initialized an object’s properties as you created it with an object initializer. We showed how to define the behavior of the built-in operators on objects of your own classes with operator overloading, and demonstrated how to create your own value types with struct
. Finally, we showed how to use extension methods to add capabilities to existing types without modifying their source code.
In the next chapter, you’ll learn about inheritance. You’ll see that all classes in C# are related directly or indirectly to the object
root class and begin to understand how inheritance enables you to build related classes faster.