maliks
maliks

Reputation: 1112

Accessing/Using nested classes from other classes C#

I have a class in a folder in my namespace as:

using System;  

namespace mynamespace.myFolder1
{
   public class F1  
   {  
      // class properties...  
      // class methods...  

      public class F1_Nest  
      {  
          // class properties...  
          // class methods...  
      }  
}

Now I have to access class F1_Nest as from:

using System;  
using mynamespace.myFolder1;   

namespace mynamespace.myFolder2  
{  
   public class F2  
   {  
      // class properties...  
      // class methods...  

      // I have to access nested class F1_Nest here...  
   }  
}

How will I use/access class F1_Nest inside class F2?

Upvotes: 0

Views: 130

Answers (4)

Md.Rajibul Ahsan
Md.Rajibul Ahsan

Reputation: 1

Declare the object of F1_Nest as follows

F1.F1_Nest  objYourObjectVariableName=new F1.F1_Nest();

Upvotes: 0

rory.ap
rory.ap

Reputation: 35260

A nested class is just like a normal class, except it's definition resides within the containing class. The result is that the containing class is almost like a namespace for the nested class. You don't have to instantiate the containing class in order to use the nested class. For instance:

namespace MyNamespace
{
    public class MyParentClass
    {
        public class MyNestedClass
        {

        }
    }
}

Now you can instantiate it somewhere else like this:

MyNamespace.MyParentClass.MyNestedClass x = 
    new MyNamespace.MyParentClass.MyNestedClass();

The purpose of this, like namespaces, is for organization. It's up to you as the designer whether or not you use nested classes instead of a flat class structure, but it can be convenient when you have a class whose meaning, definition, or usage is inextricably tied to the another class and doesn't have any relevance or meaning outside of that class.

For example, imagine you have a Widget class which has an ID property that's more than just a simple int or Guid...you might have a WidgetID enumeration, for example that could reside as a nested class in Widget.

Upvotes: 1

maliks
maliks

Reputation: 1112

The nested class F1_Nest can be accessed in class F2 as:

using System;  
using mynamespace.myFolder1;   

namespace mynamespace.myFolder2  
{  
   public class F2  
   {  
      // class properties...  
      // class methods...  

      // I have to access nested class F1_Nest here...  
      void F2_Method()  
      {
         F1.F1_Nest();  
      }
   }  
}

Upvotes: 0

MaKCbIMKo
MaKCbIMKo

Reputation: 2820

To access nested classes you need to do the following:

using System;  
using mynamespace.myFolder1;   

namespace mynamespace.myFolder2  
{  
    public class F2  
    {  
        // class properties...  
        // class methods...  

        void SomeMethod()
        {
            // no need to instantiate an object of F1 class
            var f1Nest = new F1.F1_Nest();
        }  
    }  
}

Upvotes: 0

Related Questions