Nested classes are different from sub-classes in the the way they can access the properties and private fields of the container class when inheriting from it.
Nested classes represent the combining of inheritance with encapsulation in OOP, in terms of a singleton design pattern implementation, where dependencies are well hidden and one class provide a single point of access with static access to the inner classes, while maintaining the instantiaion capability.
For example using practical class to connect to 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 WebDemoContext
and in the same time inheriting from WebDemoContext
in that way the nested class can access all the members of the container class including private members which can be effective in reducing DRY and achieving SOC.