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

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.

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;  
        }
    }
    

Need Your Help

Django: Calling save() on FileField using field name as string

python django django-forms filefield setattr

Please help, I am quite new to Django and already have read and tried everything that came into my mind.

Handling WCF Rest Service exceptions only in one place

c# wcf rest

I'm developing an WCF Rest service that I'm going to host on an IIS.