What is C# (C Sharp) Nested Type?The classes
and structures you normally code are declared within a namespace. Such
classes and structures are known as non-nested types. You can define a
class or structure within another class or structure. Such inner level
classes or structures are known as nested types. This article will help
you in understanding nested types with relevant examples.
Here is a simple example for nested types: class sampleClass
{ How Do You Access Nested Types? In the above example, you need to access sampleInt of nestedType from outside. How do you do it? You can do it in two ways. 1. Creating an instance of nested type within the class that contains it You can create
instance of nestedType inside Main method of sampleClass as shown below: Output of this code will be: The Value is: 1500 2. Creating an instance of nested type in another class If you want to access member of a nested type from another class which does not contain the nested type, then you have to ensure that the nested type has enough visibility. When you dont associate any modifier to the nested type, it becomes a private member of the containing class. In the example discussed above, nestedType doesnt have any access modifier associated hence it is a private member of sampleClass. Now if you have to access it outside sampleClass, you have to make it public as shown in the code below: class sampleClass
{ Output of this code will be same as the output shown above. In this code, you have done two changes compared to the earlier code. You have made the nestedType as public and to create instance of nestedType, you have used the fully qualified name sampleClass.nestedType instead of nestedType. Can You Access Outer Class Variables From Inside Nested Type? Yes you can very well access outer class variables from nested type, but you have to create an instance of outer class inside the nested type and access the outer class members using that instance variable. Here is an example to demonstrate it: class sampleClass
{ Output of this code will be: Multiplication Result is: 15000 In this example, you try to access sampleClassVar of outer class named sampleClass from inside the inner class called nestedType. To do so, you create an instance of sampleClass inside nestedType and access sampleClassVar using that instance. Can You Inherit Nested Type? Yes. Nested types can be inherited. This is demonstrated using the example shown below: class sampleClass
{ Output of this code will be: Inside nestedType
Class
Even though nested types can be accessed from other classes, it is not recommendable. Use nested types only when their scope, visibility and life time ends within the outer class and they are not exposed to other classes. And use nested type only when your requirement demands it. Do not use it frequently.
|