Object Oriented Programming and C#: Nested Classes

If you have spent enough time writing computer programs, you have most likely come across a situation in which you needed to “nest” a function inside a function. With object oriented programming, this can also be done with classes, as shown below.

nest

As shown, the classes “Dogs” and “Cats” are nested inside the class “Animals”. Normally, a class is placed within the namespace, but a nested class is defined within another class. Nested classes have special privileges to objects defined from the parent class. Generally the nested class is not meant to be used on its own but is usually used when a special relationship exists between the class and its parent that requires access to private information. It is important to note that in order to access the nested class, the parent class must be referenced as well, as shown below. The nested class can be instantiated just like the parent class.

nested

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s