TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Nested Class

This C# example program uses nested classes. It explains the concept of nesting.

Nested class. What is a nested class?

And when should you use nested classes in your C# programs? Nested classes refer to class declarations that occur in other class declarations. They are sometimes useful.

Example. The class B here is enclosed inside the declaration of class A. Class B is thus a nested class. Because it has a public accessibility modifier, it can be accessed in places other than class A's scope.

Here: We create an instance of A and an instance of A.B. The instance of A does not contain an instance of B.

C# program that shows nested class B

class A
{
    public int _v1;

    public class B
    {
	public int _v2;
    }
}

class Program
{
    static void Main()
    {
	A a = new A();
	a._v1++;

	A.B ab = new A.B();
	ab._v2++;
    }
}

Types versus instances. The important point about nested classes is that you are declaring types, not member fields. It happens to be possible to enclose one type declaration in another, but they do not merge into the same type.

Inheritance. If you want to merge two types into one type, it is best to use inheritance. If you had class B inherit from class A, class B would have both the _v1 and _v2 fields available. Derived classes are not nested classes.

Note: Derivation doesn't involve the textual position of classes but rather their runtime characteristics.

Also, you can have one class instance be stored inside another class. Simply add a member field of the class type to the class where you want to store it. This is also not a nested class, but simply a member field.

Tip: This approach can be more useful than inheritance when the classes are not conceptually related.

Summary. We explored the conceptual of nested classes in the C# language. Nested classes are determined by the lexical position of the type declarations. Nesting does impact accessibility domains of the nested class as well.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf