
Defining Nested Types
In addition to defining class fields, methods, and properties, you can also define another type within the class.
This is called a nested type. Nested types can be declared public, private, internal, or protected. Non-nested
types can only be declared public or private.
public class OuterClass
{
// A public nested type can be used by anybody.
public class PublicInnerClass
{}
// A private nested type can only be used by members
// of the containing class.
private class PrivateInnerClass
{}
}
To use a public nested type from outside the containing type, simply qualify the name with the containing type.
static void Main(string[] args)
{
// Create and use the public inner class. OK!
OuterClass.PublicInnerClass inner;
inner = new OuterClass.PublicInnerClass();
// Compile error! Cannot access the private class.
OuterClass.PrivateInnerClass inner2;
inner2 = new OuterClass.PrivateInnerClass();
}
Only the containing class can use a privately nested type.
public class OuterClass
{
private class PrivateInnerClass
{}
// OK! Containing class can use the private nested class.
private PrivateInnerClass mInner = new PrivateInnerClass();
void SomeMethod()
{
PrivateInnerClass inner = new PrivateInnerClass();
}
}
Why would you use a nested type?
This is similar to composition (Has-A) except that you have complete control over the access level of the inner
type instead of the inner object. Also, because a nested type is a member of the containing class, it can access
private members of the containing class. Sometimes a nested type is only a helper for the outer class and is not
intended for use by the outside world.
For example, make BenefitsPackage a nested class of Employee.
public class Employee
{
private double mWage, mHours;
public class BenefitPackage
{
public double ComputePayDeduction()
{ return 125.0; }
public double Compute401kContribution(Employee emp)
{
// Use Employee private fields to compute 401K contribution.
return emp.mWage * emp.mHours * .15;
}
}
}
One typical use of nested types is to define a nested enumeration. An enumeration is a type that contains a set
of named constants. You will see enumerations in detail in an upcoming chapter. If the enumeration is logically
tied to a class, you may nest the enumeration within the class.
public class BenefitPackage
{
// A nested enum to represent different benefit package levels.
public enum BenefitPackageLevel
{
// These are named constants for 0, 1, and 2, respectively.
Standard, Gold, Platinum
}
public BenefitPackage(BenefitPackageLevel packageLevel)
{ // ...
}
}
Defining Nested Types
Table of Contents
C# Tutorial | C#.NET Tutorial | Interfaces Tutorial
Copyright (c) 2008. Intertech, Inc. All Rights Reserved. This information is to be used exclusively as an online learning aid. Any attempts to copy, reproduce, or use for training is strictly prohibited.
|
Courseware
Training Resources
Tutorials
Services