Nested classes differ from subclasses in how they can access the properties and private fields of a container class when inheriting from it.
Nested classes are a combination of inheritance and encapsulation in OOP in terms of implementing a singleton design template, where dependencies are well hidden, and one class provides a single access point with static access to internal classes, while instant capability is supported.
For example, using a practical class to connect to a database and insert data:
public class WebDemoContext { private SqlConnection Conn; private string connStr = ConfigurationManager.ConnectionStrings["WebAppDemoConnString"].ConnectionString; protected void connect() { Conn = new SqlConnection(connStr); } public class WebAppDemo_ORM : WebDemoContext { public int UserID { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public string Phone { get; set; } public string Email { get; set; } public string UserName { get; set; } public string UserPassword { get; set; } public int result = 0; public void RegisterUser() { connect(); SqlCommand cmd = new SqlCommand("dbo.RegisterUser", Conn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("FirstName", FirstName); cmd.Parameters.AddWithValue("LastName", LastName); cmd.Parameters.AddWithValue("Phone", Phone); cmd.Parameters.AddWithValue("Email", Email); cmd.Parameters.AddWithValue("UserName", UserName); cmd.Parameters.AddWithValue("UserPassword", UserPassword); try { Conn.Open(); result = cmd.ExecuteNonQuery(); } catch (SqlException se) { DBErrorLog.DbServLog(se, se.ToString()); } finally { Conn.Close(); } } } }
The WebAppDemo_ORM
class is a nested class inside a WebDemoContext
and at the same time inherits from WebDemoContext
so that the nested class can access all members of the container class, including private members that can be effective in reducing DRY and achieving SOC .
source share