Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access a non-static member of outer type via nested type

Tags:

c#

class

I have error

Cannot access a non-static member of outer type 'Project.Neuro' via nested type 'Project.Neuro.Net'

with code like this (simplified):

class Neuro
{
    public class Net
    {
        public void SomeMethod()
        {
            int x = OtherMethod(); // error is here
        }
    }

    public int OtherMethod() // its outside Neuro.Net class
    {
        return 123;  
    }
}

I can move problematic method to Neuro.Net class, but I need this method outside.

Im kind of objective programming newbie.

Thanks in advance.

like image 358
Kamil Avatar asked May 01 '13 15:05

Kamil


2 Answers

The problem is that nested classes are not derived classes, so the methods in the outer class are not inherited.

Some options are

  1. Make the method static:

    class Neuro
    {
        public class Net
        {
            public void SomeMethod()
            {
                int x = Neuro.OtherMethod(); 
            }
        }
    
        public static int OtherMethod() 
        {
            return 123;  
        }
    }
    
  2. Use inheritance instead of nesting classes:

    public class Neuro  // Neuro has to be public in order to have a public class inherit from it.
    {
        public static int OtherMethod() 
        {
            return 123;  
        }
    }
    
    public class Net : Neuro
    {
        public void SomeMethod()
        {
            int x = OtherMethod(); 
        }
    }
    
  3. Create an instance of Neuro:

    class Neuro
    {
        public class Net
        {
            public void SomeMethod()
            {
                Neuro n = new Neuro();
                int x = n.OtherMethod(); 
            }
        }
    
        public int OtherMethod() 
        {
            return 123;  
        }
    }
    
like image 69
D Stanley Avatar answered Nov 16 '22 02:11

D Stanley


you need to instantiate an object of type Neuro somewhere in your code and call OtherMethod on it, since OtherMethod is not a static method. Whether you create this object inside of SomeMethod, or pass it as an argument to it is up to you. Something like:

// somewhere in the code
var neuroObject = new Neuro();

// inside SomeMethod()
int x = neuroObject.OtherMethod();

alternatively, you can make OtherMethod static, which will allow you to call it from SomeMethod as you currently are.

like image 38
vlad Avatar answered Nov 16 '22 01:11

vlad