bayCoder
bayCoder

Reputation: 1355

Inheritance + NestedClasses in C#

We can have nested classes in C#. These nested classes can inherit the OuterClass as well. For ex:

public class OuterClass
{
  // code here
  public class NestedClass : OuterClass
  {
    // code here
  }
}

is completely acceptable.

We can also achieve this without making NestedClass as nested class to OuterClass as below:

public class OuterClass
{
  // code here
}

public class NestedClass : OuterClass
{
  // code here
}

I am wondering, what is the difference between above two scenarioes? What is achievable in scenario I which can't be achievable in scenario II? Is there anything that we get more by making NestedClass "nested" to OuterClasss?

Upvotes: 11

Views: 10435

Answers (4)

Ashraf Sada
Ashraf Sada

Reputation: 4905

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.

Upvotes: 1

siamak
siamak

Reputation: 677

Its maybe too late But Let me Add my 2 cents Please , If I could understand your question correctly , You mean :

What is the advantage of a nested class that also inherited from its outer class?

The key point is in Construction

First Code :

    public class OuterClass
{
    public OuterClass{console.writeln("OuterClaass Called");}

  public class NestedClass : OuterClass //It does Inherit
  {
    public NestedClass{console.writeln("NestedClass Called");}
  }
}

static void Main()
{
  outerClass.NestedClass nestedobject = new outerClass.NestedClass();
}

OutPut :

Outerclass Called

NestedClass Called

Second Code :

public class OuterClass
{
    public OuterClass{console.writeln("OuterClaass Called");}

  public class NestedClass //it dosent Inherit
  {
    public NestedClass{console.writeln("NestedClass Called");}
  }
}

static void Main()
{

  OuterClass.NestedClass nestedobject = new OuterClass.NestedClass();
}

Output :

NestedClass called


In the first code when constructing the NestedClass object , the Constructor of the OutrClass also would be Called and In my opinion it means Composition Relationship between NestedClass and The OuterClass But In the Second Code Object Construction of the NestedClass and the Outerclass Is not bounded together and its done independently .

hope it would be helpfull.

Upvotes: 4

yas4891
yas4891

Reputation: 4862

the second example you provided is not a nested class, but a normal class that derives from OuterClass.

  • nested types default to private visibility, but can be declared with a wider visibility
  • nested types can access properties, fields and methods of the containing type (even those declared private and those inherited from base types)

also take a look at this question here on when and why to use nested classes.
MSDN link : Nested Types (C# Programming Guide)

EDIT
To address @Henk's comment about the difference in nature of the both relations (inheritance vs. nested types): In both cases you have a relation between the two classes, but they are of a different nature. When deriving from a base class the derived class inherits all (except private) methods, properties and fields of the base class. This is not true for nested class. Nested classes don't inherit anything, but have access to everything in the containing class - even private fields, properties and methods.

Upvotes: 17

BoltClock
BoltClock

Reputation: 724552

Inheriting from a parent class does not allow a nested class to see its parent's private members and methods, only protected (and public) ones. Nesting it within the parent class lets it see all private members and invoke its private methods, whether the nested class inherits from the parent class or not.

Upvotes: 6

Related Questions